async Task DoAsync()
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
await Task.Delay(TimeSpan.FromSeconds(3));
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
async Task DoAsync()
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
await Task.Delay(TimeSpan.FromSeconds(3)).ConfigureAwait(false);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
Stephen Clearly mentions a deadlock situation in his famous book, where ConfigureAwait helps in breaking the deadlock. Let’s consider the deadlock situation first.
private async void button1_Click(object sender, EventArgs e)
{
Task temp = DoAsync();
Debug.WriteLine("Continue");
temp.Wait();
Debug.WriteLine("Not Deadlock");
}
async Task DoAsync()
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
await Task.Delay(TimeSpan.FromSeconds(3));
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
The above code would end up in a deadlock. This is because, in the DoAsync Method, the captured context in which the execution needs to continue, has a thread which is already blocked by the Wait Method in the calling Button_Click event. Since the context only allows a single thread to continue, this would result in a deadlock situation. This could be resolved if we switch context in the await method.