Async Await in Web Service Design

Have been wanting to understand the Async Await Pattern in all its glory. Recently got the opportunity to finally jump head on

Tips:

  • 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.
    • https://msdn.microsoft.com/en-us/library/hh191443.aspx

 

  • UI thread of an ASP.NET application needs special handling. Else there could be deadlock issues
    • http://blog.ciber.no/2014/05/19/using-task-configureawaitfalse-to-prevent-deadlocks-in-async-code/
    • 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.
      • http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx

 

  • For debugging : Use Debug.WriteLine and use the ‘Output’ windows in VS

 

Code:

References:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s