async / await: If it doen't use threads what is it doing to running processing at the same time?

Viewed 497

I am doing a little research to understand async / await of C# better.

I found a web site that has the following code to show how much slower synchronous processing is vs async / await:

 public IActionResult Index()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var content = service.GetContent();
            var count = service.GetCount();
            var name = service.GetName();

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;

            return View();
        }

        [HttpGet]
        public async Task<ActionResult> IndexAsync()
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            ContentManagement service = new ContentManagement();
            var contentTask = service.GetContentAsync();
            var countTask = service.GetCountAsync();
            var nameTask = service.GetNameAsync();

            var content = await contentTask;
            var count = await countTask;
            var name = await nameTask;

            watch.Stop();
            ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
            return View("Index");
        }


        public class ContentManagement
        {
            public string GetContent()
            {
                Thread.Sleep(2000);
                return "content";
            }

            public int GetCount()
            {
                Thread.Sleep(5000);
                return 4;
            }

            public string GetName()
            {
                Thread.Sleep(3000);
                return "Matthew";
            }
            public async Task<string> GetContentAsync()
            {
                await Task.Delay(2000);
                return "content";
            }

            public async Task<int> GetCountAsync()
            {
                await Task.Delay(5000);
                return 4;
            }

            public async Task<string> GetNameAsync()
            {
                await Task.Delay(3000);
                return "Matthew";
            }
        }

I understand the above code at a high level and why it performs faster.

What I don't understand is if threads are not being used, how is the processing running at the same time?

I have read in a couple of places that async / await does not create new threads to do the processing. So, what is async / await doing to allow processing to happen at the same time? The three await Task.Delay are running in parallel, correct? If it is not creating 3 threads, what is it doing?

I just want to understand what is happening at a high level.

Let me know.

Thanks in advance.

2 Answers
Related