async execution is different from expected

bui*_*ete 1 c# asynchronous async-await

in the following snippet

    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");
    }
Run Code Online (Sandbox Code Playgroud)

I call FinishCommandExecute (it is bound to a button as command), and I would expect the finish command would call the flush command and wait for it to finish, but it doesn't wait past the await inside the flush command...and the execution continues

if you look at the comment, I would expect the following in the console

  • FinishCommandExecute_1
  • FinishCommandExecute_2
  • FlushCommandExecute_1
  • FlushCommandExecute_2
  • FlushCommandExecute_3
  • FlushCommandExecute_4
  • FinishCommandExecute_3
  • FinishCommandExecute_4

while the actual is:

  • FinishCommandExecute_1
  • FinishCommandExecute_2
  • FlushCommandExecute_1
  • FlushCommandExecute_2
  • FinishCommandExecute_3
  • FinishCommandExecute_4
  • FlushCommandExecute_3
  • FlushCommandExecute_4

why doesnt async wait for the task run in the second async method

AAA*_*ddd 5

FlushCommandExecute is an async void, so it runs unobserved, you cant await\wait for it unless you use some sort of synchronisations mechanism like a AutoResetEvent ect or refactor your code to call async Task and await that.

private async void FlushCommandExecute() => await FlushCommand();

private async void FinishCommandExecute()
{
    ...
    await FlushCommand();
    ...
}

private async Task FlushCommand()
{
     ...
}
Run Code Online (Sandbox Code Playgroud)