C#C
C#3y ago
hugeman

❔ async void in event handler (window "OnClosing" event)

I have this code here which obviously shouldn't work due to how async void and Task.Delay naturally work:
private async void OnClosing(object sender, CancelEventArgs e) {
    await Task.Delay(1000); // or maybe replace with awaitable background work 
    e.Cancel = true;
}

As soon as you call Task.Delay, is returns a non-completed task and the async state machine now has to go into plan B and use the execution context, but async void can't really "wait" there until it's done so it just returns, meaning e.Cancel is always false by the time the method returns

So how would you actually make this work, even if the code looks slightly dirtier... would you even be able to use the OnClosing event at all?
Was this page helpful?