在下面的代碼片段中 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條經驗 獲得超8個贊
FlushCommandExecute是async void,因此它運行時未觀察到,您無法等待\等待它,除非您使用某種同步機制(如AutoResetEvent等)或重構代碼來調用async Task并等待它。
private async void FlushCommandExecute() => await FlushCommand();
private async void FinishCommandExecute()
{
...
await FlushCommand();
...
}
private async Task FlushCommand()
{
...
}
- 1 回答
- 0 關注
- 205 瀏覽
添加回答
舉報
0/150
提交
取消