Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the use of async/await create a new thread?

I am new to TPL and I am wondering: How does the asynchronous programming support that is new to C# 5.0 (via the new async and await keywords) relate to the creation of threads?

Specifically, does the use of async/await create a new thread each time that they are used? And if there many nested methods that use async/await, is a new thread created for each of those methods?

like image 434
dev hedgehog Avatar asked Dec 03 '14 07:12

dev hedgehog


People also ask

Does await spawn a thread?

Using Async/Await doesn't necessarily cause a new thread to be created. But the use of Async/Await can lead to a new thread to be created because the awaitable function may internally spawn a new thread. And it often does, making the statement 'No, it doesn't spawn threads' almost useless in practice.

Does async run on a separate thread?

Async programming is about non-blocking execution between functions, and we can apply async with single-threaded or multithreaded programming. So, multithreading is one form of asynchronous programming.

Does async await block the thread?

The await operator doesn't block the thread that evaluates the async method. When the await operator suspends the enclosing async method, the control returns to the caller of the method.

What happens during async await?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.

Do await and async methods require multithreading?

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

How does await work in async?

Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

Does async/await spawn new threads?

Using Async/Await doesn't necessarily cause a new thread to be created. But the use of Async/Await can lead to a new thread to be created because the awaitable function may internally spawn a new thread. And it often does, making the statement 'No, it doesn't spawn threads' almost useless in practice.

What happens when an async method is suspended at await?

In the meantime, control returns to the caller of the async method. The suspension of an async method at an await expression doesn't constitute an exit from the method, and finally blocks don't run. The marked async method can itself be awaited by methods that call it.


2 Answers

In short NO

From Asynchronous Programming with Async and Await : Threads

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

like image 89
Adriaan Stander Avatar answered Oct 09 '22 02:10

Adriaan Stander


According to MSDN : async keyword

An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example in the next section shows.

Here is a sample code to check it :

class Program  {     static void Main(string[] args)     {         Program p = new Program();         p.Run();     }      private void Print(string txt)     {         string dateStr = DateTime.Now.ToString("HH:mm:ss.fff");         Console.WriteLine($"{dateStr} Thread #{Thread.CurrentThread.ManagedThreadId}\t{txt}");     }      private void Run()     {         Print("Program Start");         Experiment().Wait();         Print("Program End. Press any key to quit");         Console.Read();     }      private async Task Experiment()     {         Print("Experiment code is synchronous before await");         await Task.Delay(500);         Print("Experiment code is asynchronous after first await");     } } 

And the result : Experiment result: the code after the await executes in another Thread

We see the code of Experiment() method after await executes on another Thread.

But if I replace the Task.Delay by my own code (method SomethingElse) :

   class Program {     static void Main(string[] args)     {         Program p = new Program();         p.Run();     }      private void Print(string txt)     {         string dateStr = DateTime.Now.ToString("HH:mm:ss.fff");         Console.WriteLine($"{dateStr} Thread #{Thread.CurrentThread.ManagedThreadId}\t{txt}");     }      private void Run()     {         Print("Program Start");         Experiment().Wait();         Print("Program End. Press any key to quit");         Console.Read();     }      private async Task Experiment()     {         Print("Experiment code is synchronous before await");         await SomethingElse();         Print("Experiment code is asynchronous after first await");     }      private Task SomethingElse()     {         Print("Experiment code is asynchronous after first await");         Thread.Sleep(500);         return (Task.CompletedTask);     } } 

I notice the thread remains the same !

The thread is the same even with async/await

In conclusion, I'll say async/await code could use another thread, but only if the thread is created by another code, not by async/await.

In this case, I think Task.Delay created the thread, so I can conclude async/await does not create a new Thread like said by @Adriaan Stander.

like image 28
Elo Avatar answered Oct 09 '22 03:10

Elo