C
C#16mo ago
br4kejet

❔ 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;
}
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?
1 Reply
Accord
Accord15mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.