private async void MyHandler(object sender, EventArgs args)
{
await DoSomethingAsync();
DoSomethingElse();
}
The execution path of this function completely executes DoSomethingAsync()
,
then runs DoSomethingElse()
. The exact thread that both of these operations run on is undefined (meaning it can run anywhere). Additionally, any errors in DoSomethingAsync
will prevent DoSomethingElse()
from running, and will call an event handler on your SynchronizationContext
sometime down the line alerting you of the failure.
private void MyHandler(object sender, EventArgs args)
{
_ = DoSomethingAsync();
DoSomethingElse();
}
The execution path of this function runs DoSomethingAsync()
until the first await
expression, where it schedules the execution of the rest of DoSomethingAsync()
. It will then run DoSomethingElse()
synchronously.
This means that everything after the first await
of DoSomethingAsync
can run anywhere, at any time, and is not necessarily going to run before DoSomethingElse()
. You will never know if any await
s in DoSomethingAsync
run at all, or whether it runs successfully, as any errors in DoSomethingAsync()
will not prevent DoSomethingElse()
from running (including those in the synchronous block!). In practice, if this is all you need from this pattern, then you should just use try/catch.
To clarify, The first synchronous block of DoSomethingAsync()
will run until the first await. After that, you are in the blind. Note that DoSomethingAsync
failing in your void
pattern will behave exactly the same as MyHandler
failing in your async void
pattern.
Your first pattern (async void
) strongly defines the control-flow (do A, then do B), while your second (void
) pattern loosely defines the control flow (do A until the first await
, do B, and sometime in the future finish doing A.).
Note that both patterns are exactly the same to whatever code is calling your event handler; each just has different benefits and consequences for your end of the stick.
You can read more about return types and exception behavior with these patterns here: