在下面的片段中
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(它作为命令绑定(bind)到一个按钮), 我希望 finish 命令 会调用 flush 命令 并等待它完成,但它不会等待 flush 命令中的等待...并且执行继续
如果您查看评论,我会期望控制台中出现以下内容
- FinishCommandExecute_1
- 完成命令执行_2
- FlushCommandExecute_1
- FlushCommandExecute_2
- FlushCommandExecute_3
- FlushCommandExecute_4
- 完成CommandExecute_3
- 完成CommandExecute_4
而实际是:
- FinishCommandExecute_1
- FinishCommandExecute_2
- FlushCommandExecute_1
- FlushCommandExecute_2
- 完成CommandExecute_3
- 完成CommandExecute_4
- FlushCommandExecute_3
- FlushCommandExecute_4
为什么在第二种异步方法中不异步等待任务运行
最佳答案
FlushCommandExecute
是一个async void,所以它运行未被观察到,你不能等待\等待它,除非你使用某种同步机制,如 AutoResetEvent
等,或重构您的代码以调用 async Task
并等待它。
private async void FlushCommandExecute() => await FlushCommand();
private async void FinishCommandExecute()
{
...
await FlushCommand();
...
}
private async Task FlushCommand()
{
...
}
关于c# - 异步执行与预期不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162117/