Have been wanting to understand the Async Await Pattern in all its glory. Recently got the opportunity to finally jump head on
- Async Await & Threading :
- Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method. 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. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn’t help with a process that’s just waiting for results to become available.
- UI thread of an ASP.NET application needs special handling. Else there could be deadlock issues
- Interestingly I found Console Apps can automatically handle this issue by spawning a different thread. But ASP.NET Apps require you to explicitly put in the .ConfigureAwait(false)
- e.g. result = await DoSomeTask().ConfigureAwait(false)
- The reason the Console Apps behave differently is very well explained in the link below :
- All of the UI application types you can create in Visual Studio will end up having a special SynchronizationContext published on the UI thread. Windows Forms, Windows Presentation Foundation, Metro style apps… they all have one. But there’s one common kind of application that doesn’t have a SynchronizationContext: console apps.
- For debugging : Use Debug.WriteLine and use the ‘Output’ windows in VS
- Asynchronous Programming with Async and Await
- Control Flow in Async Programs