Task.delay永远不会完成

问题描述 投票:0回答:1

以下代码将永远冻结。

public async Task DoSomethingAsync() { await Task.Delay(2000); } private void Button_Click(object sender, RoutedEventArgs e) { DoSomethingAsync().Wait(); // Task.Delay(2000).Wait(); }
如果我将呼叫转换为

DoSomethingAsync

带有评论的代码,则表现为预期。我怀疑以某种方式嵌套的等待造成了僵局,但我不确定为什么或如何修复它。
    

the the the the the thread the the the the the the the僵局。
c# .net task-parallel-library async-await delay
1个回答
47
投票
Button_Click

时,您要同步阻止线程直到任务结束,但是任务将永远不会结束,因为延续(

GUI
的完成)也必须在GUI线程上运行(已阻止在
Wait

上 您有几种解决方案。要么使用

Task.Delay(2000);

不捕获GUI线程的同步context:
Wait).
或(我建议)使用
ConfigureAwait(false)

事件处理程序(这是

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

方法的唯一合适位置):

async void
    

我遇到了一个单独的问题,即永不返回。此延迟调用是在一个工作函数中嵌套在父任务中的多个功能。对我有用的解决方案是使用此通话:

async void

	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.