Cannot prevent closing of a window if use async OnClosingHandler
See original GitHub issueI have code like this in my window class.
{
// in constructor
this.Closing += OnStandardClosing;
}
private async void OnStandardClosing(object? sender, System.ComponentModel.CancelEventArgs e)
{
if(!await CheckMaybeSavingOnClose())
{
e.Cancel = true;
}
}
But my window closes before I am will be able to choose an option before closing.
I tried to switch to syncronous handling by blocking on task but this prevent the second window from interactivity.
The other thing I tried is adding Task
type to OnStandardClosing but this doesn’t compile.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (4 by maintainers)
Top Results From Across the Web
Cannot use async in closing method
1 Answer 1 ... The OP has no idea whether they want to cancel the closing or not before they call the method....
Read more >Cancel async tasks after a period of time
In this article. You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if ...
Read more >Using Async, Await, and Task to keep the WinForms UI ...
The problem is that a long-running job running on the UI thread freezes the app. Even short job will lock the UI for...
Read more >Understanding Control Flow with Async and Await in C# | ...
Even if the underlying task is asynchronous, if you call a blocking method or blocking property on the task, execution will wait for...
Read more >Cancel async task: best practice?
Now, when I use a UniTask instead, I cannot cancel it from the outside. I will either have it end itself or use...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
async void
is essentiallyso your OnStandardClosing returns immediately.
You need to cancel the close right away and close the window manually if
CheckMaybeSavingOnClose
returns trueNevermind, figured it out! I needed to remove the function call from Closing, this helped me: https://stackoverflow.com/questions/49012892/cannot-use-async-in-closing-method