在下面的代码片段中 private async void FinishCommandExecute() { Console.WriteLine("FinishCommandExecute_1"); _granularBlobAnalyzer.SaveResult(SampleID, Operator, Comments); Console.WriteLine("FinishCommandExecute_2"); await Task.Run(() => FlushCommandExecute()); Console.WriteLine("FinishCommandExecute_3"); State = GBAState.IDLE; Console.WriteLine("FinishCommandExecute_4"); } private async void FlushCommandExecute() { Console.WriteLine("FlushCommandExecute_1"); State = GBAState.FLUSHING; Console.WriteLine("FlushCommandExecute_2"); await Task.Run(() => _granularBlobAnalyzer.Flush()); // Task to wrap sync method Console.WriteLine("FlushCommandExecute_3"); State = GBAState.STOPPED; Console.WriteLine("FlushCommandExecute_4"); }我调用 FinishCommandExecute (它作为命令绑定到一个按钮),我希望完成命令会调用刷新命令并等待它完成,但它不会等待刷新命令内的等待...并且执行继续如果您查看评论,我希望控制台中出现以下内容完成命令执行_1完成命令执行_2FlushCommandExecute_1FlushCommandExecute_2FlushCommandExecute_3FlushCommandExecute_4完成CommandExecute_3完成CommandExecute_4而实际情况是:完成命令执行_1完成命令执行_2FlushCommandExecute_1FlushCommandExecute_2完成CommandExecute_3完成CommandExecute_4FlushCommandExecute_3FlushCommandExecute_4为什么异步方法不等待第二个异步方法中的任务运行
1 回答
largeQ
TA贡献2039条经验 获得超7个赞
FlushCommandExecute是async void,因此它运行时未观察到,您无法等待\等待它,除非您使用某种同步机制(如AutoResetEvent等)或重构代码来调用async Task并等待它。
private async void FlushCommandExecute() => await FlushCommand();
private async void FinishCommandExecute()
{
...
await FlushCommand();
...
}
private async Task FlushCommand()
{
...
}
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报
0/150
提交
取消