0

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)); } 
4
  • Make event handler async and await call to Task.Run inside it? Commented Dec 27, 2019 at 3:32
  • @balbelias, I tried, it closes the window immediately. I need to close the window after completing MainWindow_Closing method Commented Dec 27, 2019 at 3:36
  • And what about that way: await Task.Run(new Action(ClaseAfterThreeSecond)).CondigureAwait(false);. Also get rid of Thread.Sleep in ClaseAfterThreeSecond and change it to Task.Delay. Commented Dec 27, 2019 at 3:42
  • @balbelias It didn't work. Window closes immediately Commented Dec 27, 2019 at 3:48

1 Answer 1

2

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(); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.