Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to the thread when reaching 'await' on 'async' method?

My question as the title suggest is about the background of 'async' and 'await'.

Is it true to say that what the current thread reaches 'await' keyword, it goes to "sleep", and wakes up when the await method is done?

Thanks!

Guy

like image 599
Guy Segal Avatar asked Sep 01 '12 12:09

Guy Segal


People also ask

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.

Does async await create a new thread?

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.

Does await pause the thread?

Asynchronous Methods When the executing thread reaches an await expression, it hits the “pause” button and the method execution is suspended.

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.


1 Answers

Is it true to say that what the current thread reaches 'await' keyword, it goes to "sleep", and wakes up when the await method is done?

No. The whole point of async is to avoid having threads sleeping when they could be doing other work. Additionally, if the thread running the async method is a UI thread, you really don't want it to be sleeping at all - you want it to be available to other events.

When execution reaches an await expression, the generated code will check whether the thing you're awaiting is already available. If it is, you can use it and keep going. Otherwise, it will add a continuation to the "awaitable" part, and return immediately.

The continuation makes sure that the rest of the async method gets run when the awaitable value is ready. Which thread that happens in depends on the context in which you're awaiting - if the async method is running in thread pool threads, the continuation could run on a different thread to the one the method started on... but that shouldn't matter. (The rest of the context will still be propagated.)

Note that it's fine for the async method to return without having completed - because an async method can't return a value directly - it always returns a Task<T> (or Task, or void)... and the task returned by the method will be only be completed when the async method has really reached the end.

like image 195
Jon Skeet Avatar answered Oct 02 '22 05:10

Jon Skeet