Task.Delay never completing

≯℡__Kan透↙ 提交于 2019-12-04 01:37:48

Assuming Button_Click runs in the GUI thread you have a deadlock on your hands.

When you use Wait on a task you are synchronously blocking the thread until the task ends, but the task will never end because the continuation (the completion of Task.Delay(2000);) must run on the GUI thread as well (which is blocked on Wait).

You have several solutions. Either use ConfigureAwait(false) to not capture the GUI thread's SynchronizationContext:

public async Task DoSomethingAsync()
{
    await Task.Delay(2000).ConfigureAwait(false);
}

Or (which I recommend) use an async void event handler (which is the only appropriate place for an async void method):

private async void Button_Click(object sender, RoutedEventArgs e)
{
    await DoSomethingAsync();
}

public async Task DoSomethingAsync()
{
    await Task.Delay(2000);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!