I think I have successfully confused myself for the day.
public void DoSomething1()
{
Task.Delay(1000);
}
public async void DoSomething2()
{
await Task.Delay(1000);
}
What is the difference between these two functions in terms of what happens within them when they are called? What is the purpose of using an async method that does not return a Task?
What is the difference between these two functions in terms of what happens within them when they are called?
DoSomething1 is a synchronous method. As such:
DoSomething are raised directly to the caller.DoSomething2 is an asynchronous void method. As such:
SynchronizationContext that was current at the time DoSomething2 started executing. This generally results in program termination.DoSomething2 are also raised on that SynchronizationContext, with the same result.What is the purpose of using an async method that does not return a Task?
async void is not a natural thing. For example, the equivalent simply does not exist in F#. async void was added to C#/VB to enable event handlers to become asynchronous without changing the entire event handling or delegation system.
In short, you should avoid async void, and only use them for event handlers (or logical equivalents to event handlers, like ICommand.Execute in MVVM).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With