I have a WPF app and I want to execute some method in the Closing
event. It can take several minutes, that's why the WPF window freezes. Here is my code:
public MainWindow()
{
InitializeComponent();
this.Closing += MainWindow_Closing;
}
void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Task.Run(new Action(ClaseAfterThreeSecond)).Wait();
}
void ClaseAfterThreeSecond()
{
Thread.Sleep(3000);
}
I want to do not freeze the WPF app until MainWindow_Closing
ends when I click the X button (close button) on the WPF app. Any suggestions?
EDIT: This way closes the window immediately. I don't need this:
async void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
await Task.Run(new Action(ClaseAfterThreeSecond));
}
You need to make your handler async
, but as it async void
it returns right after your first await
call. Just cancel original closing event and close directly in your code:
private async void Window_Closing(object sender, CancelEventArgs e)
{
// cancel original closing event
e.Cancel = true;
await CloseAfterThreeSeconds();
}
private async Task CloseAfterThreeSeconds()
{
// long-running stuff...
await Task.Delay(3000);
// shutdown application directly
Application.Current.Shutdown();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.