© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
1 reply
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;
}
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
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
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

async void
C#CC# / help
5mo ago
✅ Async void method testing in xUnit
C#CC# / help
12mo ago
✅ Event Handler functionality
C#CC# / help
11mo ago
automated event handler
C#CC# / help
3y ago