异步执行与预期不同

在下面的代码片段中


    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

  • 完成命令执行_2

  • FlushCommandExecute_1

  • FlushCommandExecute_2

  • FlushCommandExecute_3

  • FlushCommandExecute_4

  • 完成CommandExecute_3

  • 完成CommandExecute_4

而实际情况是:

  • 完成命令执行_1

  • 完成命令执行_2

  • FlushCommandExecute_1

  • FlushCommandExecute_2

  • 完成CommandExecute_3

  • 完成CommandExecute_4

  • FlushCommandExecute_3

  • FlushCommandExecute_4

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



蓝山帝景
浏览 113回答 1
1回答

largeQ

FlushCommandExecute是async void,因此它运行时未观察到,您无法等待\等待它,除非您使用某种同步机制(如AutoResetEvent等)或重构代码来调用async Task并等待它。private async void FlushCommandExecute() => await FlushCommand();private async void FinishCommandExecute(){    ...    await FlushCommand();    ...}private async Task FlushCommand(){     ...}
打开App,查看更多内容
随时随地看视频慕课网APP