How "async void" actually works

Let’s say I have this code (C#):

void SomeFunc()
{
    HandlerOne();
    HandlerTwo();
}

async void HandlerOne()
{
    DoX();
    await DoYAsync();
    DoZ();
}

In this case HandlerOne() will return to the calling functions the moment it hits its first await. The code is roughly equivalent to:

void HandlerOne()
{
    DoX();
    Task t= DoYAsync();
    t.ContinueWith(task=>DoZ());
}

So, there is no guarantee that DoYAsync() or DoZ() will be executed before HandlerTwo(). This is somewhat obvious after the fact (how else would one implement async void?), but I did not see it explicitly described in any documentation.

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *