简体   繁体   English

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

[英]How to do not freeze wpf app on closing event

I have a WPF app and I want to execute some method in the Closing event.我有一个 WPF 应用程序,我想在Closing事件中执行一些方法。 It can take several minutes, that's why the WPF window freezes.这可能需要几分钟,这就是 WPF 窗口冻结的原因。 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.当我单击 WPF 应用程序上的 X 按钮(关闭按钮)时,我不想在MainWindow_Closing结束之前冻结 WPF 应用程序。 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.您需要使您的处理程序async ,但由于它async void它在您的第一次await调用后立即返回。 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM