如何在关闭事件时不冻结 wpf 应用程序



我有一个 WPF 应用程序,我想在Closing事件中执行某个方法。这可能需要几分钟时间,这就是 WPF 窗口冻结的原因。这是我的代码:

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);
}

我想在MainWindow_Closing结束之前不冻结 WPF 应用程序,当我单击 WPF 应用程序上的 X 按钮(关闭按钮(之前。 有什么建议吗?

编辑:这种方式立即关闭窗口。我不需要这个:

async void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
await Task.Run(new Action(ClaseAfterThreeSecond));
}

你需要让你的处理程序async,但正如它async void它会在你第一次await调用后立即返回。只需取消原始关闭事件并直接在代码中关闭:

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();
}

最新更新