0

I have the following piece of code (WPF, Windows Phone 8.1):

HttpClient client = new HttpClient();
var httpResult = client.GetAsync(feed.Url, ct);
string feedData = await httpResult.Result.Content.ReadAsStringAsync();

var sf = new SyndicationFeed();
sf.Load(feedData);

I'm trying to debug this code. However, after the line:

string feedData = await httpResult.Result.Content.ReadAsStringAsync();

debugger seems to let application run on its own and never reaches the next line. Why is that? Am I doing something wrong?

Spook
  • 25,318
  • 18
  • 90
  • 167

1 Answers1

2

Depending on if you are calling result or wait on the task somewhere upstream, this can result in a deadlock as noted in Stephen Cleary's blog post.

Mitigate this by awaiting the client.GetAsync() and use ConfigureAwait where possible to minimize chances of deadlocks:

HttpClient client = new HttpClient();
var httpResult = await client.GetAsync(feed.Url, ct).ConfigureAwait(false);
string feedData = await httpResult.Content.ReadAsStringAsync().ConfigureAwait(false);

var sf = new SyndicationFeed();
sf.Load(feedData)
John Koerner
  • 37,428
  • 8
  • 84
  • 134
  • 1
    Also, change any upstream `Wait` or `Result` calls to use `await` instead. – Stephen Cleary Jan 10 '15 at 00:49
  • @StephenCleary Actually this was the core problem - I waited for the method I posted above via Wait. But this bothers me a little - is there a (working) way to force do some async task synchronously? – Spook Jan 10 '15 at 10:15
  • 1
    The work is being done asynchronously. The `ConfigureAwait(false)` indicates that when the work is done you don't care what thread is used to resume the rest of the work. – John Koerner Jan 10 '15 at 13:28
  • @Spook: [No](http://stackoverflow.com/questions/27869403/calling-a-3rd-party-async-task-method-synchronously/27871579#27871579). – Stephen Cleary Jan 11 '15 at 04:03
  • @StephenCleary Ok, I expressed myself wrong. By "forcing to run synchronously" I meant waiting for a Task to complete before succeeding further. This should be done by Wait, but it causes deadlocks. So is there another, proper way to do that? – Spook Jan 11 '15 at 09:01
  • @Spook: Yes, just use `await task;` instead of `task.Wait();`. – Stephen Cleary Jan 11 '15 at 13:26
  • @StephenCleary And if I don't want the calling method to be *async*? – Spook Jan 13 '15 at 17:34
  • @Spook: It's doing asynchronous work, so it should be `async`. `async` does "grow" through the code base naturally, and this should be embraced. – Stephen Cleary Jan 13 '15 at 19:57