Home > OS >  What is causing the deadlock?
What is causing the deadlock?

Time:09-10

I know this is not using the proper form, but can someone tell me why the first code snippet works and the 2nd causes a deadlock?

private void button1_Click(object sender, EventArgs e)
{
     textBox1.Text = DownloadStringV3("https://www.google.com");
}

public string DownloadStringV3(String url) 
{ 
      var resp = new HttpClient().GetAsync(url).Result;
      return resp.Content.ReadAsStringAsync().Result;
}
private void button1_Click(object sender, EventArgs e)
{
     textBox1.Text = DownloadStringV3("https://www.google.com").Result;
}

public async Task<string> DownloadStringV3(String url) 
{ 
     var resp = await new HttpClient().GetAsync(url);
     return await resp.Content.ReadAsStringAsync();
}

Different synchronization contexts? This is using .NET 4.8

CodePudding user response:

Every time you await something, you say, I am temporary done here, give some other thread a chance to execute and then continue from here, when the async task is completed.

So in your case await new HttpClient().GetAsync(url) switches the the ui thread and waiting for DownloadStringV3("https://www.google.com").Result be done, which will never be the case, because we do never execute return await resp.Content.ReadAsStringAsync().

Thats why you should do async all the way to the root and never call Result.

The first code works, because you block on the UI thread and don't try to switch to another thread, while waiting for it.

To make the second one working you need to:

private async void button1_Click(object sender, EventArgs e)
{
     // make with try catch sure, you catch any error, async void is special. Better is async Task
     textBox1.Text = await DownloadStringV3("https://www.google.com");
}

public async Task<string> DownloadStringV3(String url) 
{ 
     var resp = await new HttpClient().GetAsync(url);
     return await resp.Content.ReadAsStringAsync();
}
  • Related