Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# async await and threadpool

I understand that when using async and await on a method called on the UI thread that the UI thread can be freed to do other work while awaiting some IO to complete. If I use the async await on a method called by a threadpool thread what happens to the that threadpool thread while the IO completes? Is it returned to the pool? When the IO is completed what thread completes the method in this latter case?

like image 308
Paul Avatar asked Mar 19 '23 22:03

Paul


1 Answers

In that case, the continuation executes on any available thread-pool thread.

In theory it's up to the awaitable to schedule the continuation appropriately, but generally an awaitable captures the current SynchronizationContext when the async method passes in the continuation, and uses that synchronization context to schedule the continuation when the awaitable has completed. (Module ConfigureAwait calls etc.)

In the case of the thread pool, there is no synchronization context, so the continuation is just scheduled on any thread pool thread. (The same is true on a console app's main thread - or basically any thread where a synchronization context hasn't been set.)

like image 58
Jon Skeet Avatar answered Mar 21 '23 16:03

Jon Skeet