I’m trying to understand async await behavior and in particular how it affects the main thread, so my question is related to below code:
static async Task main(string[] args)
{
await LongAction();
}
static Task LongAction() => Task.Delay(10000);
what will happen with the main thread when LongAction is being executed. As I understand, if the the caller thread is not the main (let’s call it thread2), during the time when awaitable operation is in play, this thread (thread2) will be returned to the ThreadPool (with default task scheduler). But can it happen with the main thread (it doesn’t looks so, since initially it wasn’t taken from TP)? What if the main thread is UI thread with thread context?
>Solution :
in particular how it affects the main thread
async and await has no special behavior with any particular kind of thread, including main threads. It behaves the same way regardless of thread. Different frameworks, however, do treat main threads specially.
As I understand, if the the caller thread is not the main (let’s call it thread2), during the time when awaitable operation is in play, this thread (thread2) will be returned to the ThreadPool (with default task scheduler).
The behavior of await is always the same: if the awaitable (i.e., the task) is not yet completed, then it returns. It’s up to the framework what it does next with that thread. In the case of a thread pool thread, then yes, that thread is returned to the thread pool.
what will happen with the main thread when LongAction is being executed.
The .NET runtime includes a stub that invokes a Task-returning Main method and then just blocks that thread until the task completes. This is necessary because in console applications, if the main thread exits, the application exits.
What if the main thread is UI thread with thread context?
All UI frameworks have a "message loop" that processes messages about user input and other events. In that case, the thread just returns to its main loop and continues processing other events.