2

I'm trying to get the content of a website in a Windows 8 Metro App. I'm still a bit confused about the asyn and wait methods.
But this is what I have:

private void HelloButton_Click(object sender, RoutedEventArgs e)
{  
    GetPage().Wait();
}

private async Task GetPage()
{
      HttpClient client = new HttpClient();

      HttpResponseMessage response = await client.GetAsync("http://www.supertext.ch");
      response.EnsureSuccessStatusCode();
      string responseBody = await response.Content.ReadAsStringAsync();
}

Unfortuantely, nothing happens. If try to debug it, it just stops at GetAsync().
Do I need to make the HelloButton_Click function also async?
Even though I wait for the completion of the function GetPage()?
Can I call network requests directly from the GUI thread?

Remy
  • 12,555
  • 14
  • 64
  • 104

2 Answers2

2

Don't call Wait on the task. await it. This is a common beginners bug.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Ok, wait is just plain wrong? When would it be appropriate to use it? – Remy Nov 14 '12 at 12:55
  • 1
    @Remy wait blocks the thread, causing a deadlock. I suggest you search for "await wait deadlock" on Stack Overflow. I'm sure you'll find good material on that topic. For example: http://stackoverflow.com/questions/13140523/await-vs-task-wait-deadlock – usr Nov 14 '12 at 13:28
  • 1
    @Remy: It's almost always wrong. `Wait` is a holdover from .NET 4 and is *not* used for `async` code. I have [a blog post that describes this deadlock situation in detail](http://nitoprograms.blogspot.com/2012/07/dont-block-on-async-code.html). – Stephen Cleary Nov 14 '12 at 13:50
2

Change HelloButton_Click to :

private async void HelloButton_Click(object sender, RoutedEventArgs e)
{  
    await GetPage();
}
Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102