Sunday, December 02, 2012

.NET 4.5 Async “ConfigureAwait” – Keep the Synchronization Context in Mind

I assume you have heard about the great addition in .NET 4.5 – The Async Keyword.

It is truly one of the key changes made to the .NET language, and it is awesome. 
Asynchrony should be part of our code, there’s no escape from that.

  • If you write UI applications – you need asynchrony to avoid blocking the UI thread.
  • If you make I/O operations – you should use its asynchronous model that utilizes the I/O completion threads instead of occupying a worker thread.
  • If you build a service – you may want to implement the service using the asynchronous approach if you’re doing mainly I/O work.
  • If you want to parallelize your code – you may want to use the TPL and invoke operations asynchronously and in parallel.
  • And more..
Prior to .NET 4.5, the code looks quite awful in terms of all the nested lambda expressions, error handling, and the use of the synchronization context. 
It was also easy to make mistakes writing in this fairly complex paradigm, but I guess it comes down to the developer’s maturity and habits. I specifically got quite used to that by now, so it is all readable to me .

In .NET 4.5, Microsoft introduced us with the new ‘async’ and the ‘await’ keywords. 
The goal of this post isn’t to explain what it does, there are enough resources out there already that you can follow up on if you like to catch up.

I would like to discuss a specific feature of the ‘await’ keyword, which is continuing the execution on the captured synchronization context. 

When you write the following code -

async void Do()
{
    Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
 
    await DoSomethingAsync();
    
    Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
}
 
private Task DoSomethingAsync()
{
    return Task.Run(() =>
        {
            Thread.Sleep(1000);
 
            Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
        });
}

Q: What would be printed in line 7? Would it be the same as in line 3?

QR: Inline image 1

Posted via email from Jasper-Net