异步执行与预期的不同

时间:2019-09-30 05:51:06

标签: c# asynchronous async-await

在以下代码段中

    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(作为命令绑定到按钮), 我希望 finish命令会调用 flush命令并等待其完成,但是它不会等到flush命令中的等待状态...并且执行继续

如果您查看评论,我会在控制台中期望以下内容

  • FinishCommandExecute_1
  • FinishCommandExecute_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

为什么不异步等待任务在第二个异步方法中运行

1 个答案:

答案 0 :(得分:5)

FlushCommandExecute async void ,因此它运行 unobserved ,除非您使用{ {1}}会影响或重构您的代码以调用AutoResetEvent并等待它。

async Task