Async and await - difference between console, Windows Forms and ASP.NET
I have been educating myself on async / await use and I think I understood under-the-hood concept. However, most of Channel 9 tutorials, MSDN articles and Stack overflow answers on async / await use GUI-based applications (Windows Forms application) to demonstrate the power of async / await.
However, I noticed a fundamental difference in async / await use in a UI-thread based application vs. regular ThreadPool thread-based applications (e.g. ASP.NET Web Application, Console Application, etc.).
Since, in UI thread-based application, the UI thread is always available (unless the process is stopped explicitly or by Windows), so the ThreadPool thread responsible for executing the code after "await" in any async method, will guarantee to find the UI thread to post the results back (if any).
However, in a console application or ASP.NET Web application, the main thread (in a console application) or the HTTP request (in an ASP.NET web application) must be waiting (at one point of time) until all async operations are completed. So there should be .Wait() and .Result call somewhere after the Async method call, if there is nothing more to work on.
Is this understanding correct? I am not questioning the benefit of having async for I/O bound or network-bound operations (I understand how it's going to increase application scalability).
Solution 1:
Since, in UI thread based application, the UI thread is always available (unless the process is stopped explicitly or by Windows), so the ThreadPool thread responsible for executing the code after "await" in any async method, will guarantee to find the UI thread to post the results back (if any).
This is slightly confused. There's no indication that a ThreadPool
thread will be required at all.
It's up to the awaitable implementation to determine where to run the continuation, but normally the current synchronization context is used to work out where to run it:
- In a console application, there is no synchronization context, so a thread pool thread is used for the continuation.
- In a Windows Forms application, when you're running on the UI thread the synchronization context is one which will execute code on the UI thread... so the continuation executes there (unless you use
ConfigureAwait
, etc...) - In an ASP.NET application, there's a synchronization context specific to ASP.NET itself.
See Stephen Cleary's MSDN article for more details.
It's not clear what you mean by your later question about having to call Wait
or Result
in ASP.NET or a console app... in both scenarios it may be required, but equally it may not be. It depends on what you're doing really. Don't forget that even a console app can start its own threads and do all kinds of other things - you can write an HTTP server in a console app, for example...