NeddySpaghetti
NeddySpaghetti

Reputation: 13495

ConfigureAwait(false) still deadlocks

I've been reading up a bit on async/await and was trying to reproduce a deadlock scenario in windows forms by calling WebClient.DownloadStringTaskAsync on the UI thread and then calling task.Result on the UI thread while the task was executing. This resulted in a deadlock.

Then I tried to address the issue by calling ConfigureAwait(false) on the returned task, but to my surprise that still caused a deadlock. My understanding is that it should execute the continuation of the method on a different thread and hence there should be no deadlock. What am I missing?

I know how to get around the issue but thought ConfigureAwait(false) would fix it as well.

Here is the code, I am using NET 4.5

    private async void button1_Click(object sender, EventArgs e)
    {
        // Deadlocks!
        Task<string> task = DownloadAsync();
        textBox1.Text = task.Result;

        // Works
        //textBox1.Text = await DownloadAsync();
    }

    private static async Task<string> DownloadAsync()
    {
        var client = new WebClient();

        string result = await client.DownloadStringTaskAsync("http://www.rpmglobal.com").ConfigureAwait(false);          

        return result;
    }

Upvotes: 5

Views: 1543

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456507

WebClient will still cause this deadlock because DownloadStringTaskAsync is just a wrapper around the EAP methods, which always raise their event in the original context. There's no way to turn this off.

Try using HttpClient (or something simple like Task.Delay) to see the difference.

Upvotes: 12

Related Questions