在以下片段中

    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命令中的await并继续执行。

如果您查看评论,我希望控制台中有以下内容


FinishCommandExecute_1
FinishCommandExecute_2
FlushCommandExecute_1
FlushCommandExecute_2
FlushCommandExecute_3
FlushCommandExecute_4
FinishCommandExecute_3
FinishCommandExecute_4


而实际是:


FinishCommandExecute_1
FinishCommandExecute_2
FlushCommandExecute_1
FlushCommandExecute_2
FinishCommandExecute_3
FinishCommandExecute_4
FlushCommandExecute_3
FlushCommandExecute_4


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

最佳答案

FlushCommandExecute是一个异步void,因此它无法观察到运行,除非您使用某种同步机制(例如AutoResetEvent ect)或重构代码以调用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/

10-09 20:34
查看更多