c0D3l0g1c
c0D3l0g1c

Reputation: 3164

c# .net 4.5 async await Task.Wait() blocking issue

I have the following extension method:

internal static string ReadLine(this DataReader stream)
{
   Task<string> line = ReadLineAsync(stream);
   // line.Wait(); - Not Required, as next call blocks
   return line.Result;
}

It's basically a Synchronous method call wrapper for an Asynchronous method call that returns a string. The code works fine if I step through it line by line, however it seems that if I let it execute freely, I encounter an indefinite block. Any ideas?

Related to a previous question I posted: How can I update my API to use the async keyword without using await for all callers

Upvotes: 3

Views: 7651

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 457292

As some commented on the answer to your other question, if you use Task.Result in a GUI application, you may cause a deadlock (as I explain in detail on my blog).

In short:

  • You start the asynchronous operation on the UI thread. Note that the task line represents the ReadLineAsync method, and will complete when that method completes.
  • ReadLineAsync calls await on some operation that is incomplete. This causes ReadLineAsync to return an incomplete task (line).
  • You block the UI thread waiting for line to complete.
  • When the awaited operation completes, it schedules the remainder of ReadLineAsync to the UI thread.
  • The UI thread cannot complete ReadLineAsync because it is synchronously blocked waiting for ReadLineAsync to complete. Deadlock.

See my answer to your other question for a way around this deadlock. In short:

  • Use ConfigureAwait(false) everywhere.
  • Change your error handling to account for Result wrapping its errors in AggregateException.

Upvotes: 10

Peter pete
Peter pete

Reputation: 712

According to: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx Shouldn't you be doing:

internal static string ReadLine(this DataReader stream)
{
   string line = await ReadLineAsync(stream);
   return line
}

That said, I haven't yet started with this Async business. But I've read documentations, etc.

Upvotes: -2

Related Questions