MSDN Community / Question #12345

Why does my C# async method deadlock when called from UI thread?

Asked by JaneDoe on

I'm trying to use await inside a Windows Forms button click event, but the UI freezes indefinitely. I suspect a deadlock caused by ConfigureAwait(false). Can anyone explain what's happening and how to fix it?

c#async-awaitdeadlockwinforms
12
Answered by JohnSmith on

The deadlock occurs because the UI thread is synchronously waiting for the async operation to complete. Use await all the way up, or call .ConfigureAwait(false) on the awaited task if you don't need to resume on the UI context.

8
Answered by MikeL on

Wrap the async call in Task.Run if you must keep the event handler synchronous, but it's better to make the click handler async:

private async void button1_Click(object sender, EventArgs e)
{
    await DoWorkAsync();
}
5