Search code examples
c#.netasync-ctpasync-await

What happens to an `awaiting` thread in C# Async CTP?


I've been reading about the new async await keyword and it sounds awesome, but there is one key question I haven't been able to find the answer for in any of the intro videos I've watched so far (I also read the whitepaper a while back).

Suppose I have a call to await in a nested function on the main UI thread. What happens to the thread at this point? Does control go back to the message loop and the UI thread is free to process other inputs?

When the awaited task completes, does the entire stack get pushed onto a message queue, such that control will return through each of those nested functions, or is something else entirely happening here?

And secondly (while I have your attention), I don't really understand why asynchronous methods need to be labeled with async. Can't any method be executed asynchronously? What if I want to execute a method asynchronously but it doesn't have an async keyword--is there a way to do that simply?

Cheers. :)

Edit: Admittedly if I could get the sample code compiling I could probably just figure that out myself, but for one reason or another I'm running into a block there. What I really want to know is to what extent does a continuation continue... does it freeze the entire call stack, to resume it when the task completes, or does it only go back so far? Does a function itself need to be marked as async in order to support continuation, or (as I asked originally) does it continue the entire call stack?

If it doesn't freeze the entire call stack, what happens when the async await hits a non-async calling function? Does it block there? Wouldn't that defeat the point of await? I hope you can see that I'm missing some understanding here that I hope someone can fill in so I can continue to learn this.


Solution

  • Suppose I have a call to await in a nested function on the main UI thread. What happens to the thread at this point? Does control go back to the message loop and the UI thread is free to process other inputs?

    Yes. When you await an awaitable (such as a Task<TResult>), the thread's current position within the async method is captured. It then queues the remainder of the method (the "continuation") to be executed when the awaitable is finished (e.g., when a Task<TResult> completes).

    However, there is an optimization that can take place: if the awaitable is already finished, then await doesn't have to wait, and it just continues executing the method immediately. This is called the "fast path", described here.

    When the awaited task completes, does the entire stack get pushed onto a message queue, such that control will return through each of those nested functions, or is something else entirely happening here?

    The thread's current position is pushed onto the UI message queue. The details are a bit more complex: continuations are scheduled on TaskScheduler.FromCurrentSynchronizationContext unless SynchronizationContext.Current is null, in which case they are scheduled on TaskScheduler.Current. Also, this behavior can be overridden by calling ConfigureAwait(false), which always schedules the continuation on the thread pool. Since SynchronizationContext.Current is a UI SynchronizationContext for WPF/WinForms/Silverlight, this continuation does get pushed onto the UI message queue.

    And secondly (while I have your attention), I don't really understand why asynchronous methods need to be labeled with async. Can't any method be executed asynchronously? What if I want to execute a method asynchronously but it doesn't have an async keyword--is there a way to do that simply?

    These are slightly different meanings of the word "asynchronous." The async keyword enables the await keyword. In other words, async methods may await. Old-fashioned asynchronous delegates (i.e., BeginInvoke/EndInvoke) is quite different than async. Asynchronous delegates execute on a ThreadPool thread, but async methods execute on the UI thread (assuming that they are called from a UI context and you don't call ConfigureAwait(false)).

    If you want to have a (non-async) method run on a ThreadPool thread, you can do it like this:

    await Task.Run(() => MyMethod(..));
    

    What I really want to know is to what extent does a continuation continue... does it freeze the entire call stack, to resume it when the task completes, or does it only go back so far? Does a function itself need to be marked as async in order to support continuation, or (as I asked originally) does it continue the entire call stack?

    The current position is captured, and "resumed" when the continuation runs. Any function that uses await to support continuations must be marked async.

    If you're calling an async method from a non-async method, then you must deal with the Task object directly. This is not normally done. Top-level async methods may return void, so there's no reason not to have async event handlers.

    Note that async is purely a compiler transform. That means that async methods are exactly like regular methods after they're compiled. The .NET runtime does not treat them in any special way.