【问题标题】:How to handle the case that the progeam needs to exit before an async void event handler finishes?如何处理程序需要在 async void 事件处理程序完成之前退出的情况?
【发布时间】:2017-10-12 19:38:25
【问题描述】:

根据 MSDN,事件处理程序是 async void 唯一可接受的用法。但是如何处理程序需要在 async void 事件处理程序完成之前退出的情况呢?

我尝试了一个 WPF 应用程序,似乎程序在异步事件处理程序中的 await 行之后没有执行任何代码就退出了。这意味着可能绕过了一些清理代码,系统可能处于无效状态。

我搜索了很多,但从未见过任何评论说“如果需要任何清理,请不要使用异步事件处理程序”或类似内容。这是任何人都已经知道的非常基本的含义吗?

如果这是一个愚蠢的问题,请原谅我,因为我是 C# 世界的新手。

【问题讨论】:

标签: c#


【解决方案1】:

如果异步事件处理程序正在运行,您可以订阅Window.Closing 事件并将e.Cancel 设置为true。

public partial class MainWindow : Window
{
    //Flag indicating async operation is in progress
    private bool m_EventHandlerIsRunning = false;

    public MainWindow()
    {
        InitializeComponent();
    }

    // Subscribe this method to MainWindow's Closing event
    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        // Forbid MainWindow to close, if async event handler is running
        e.Cancel = m_EventHandlerIsRunning;
    }

    // You will have to include following in all async event handlers
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // Forbid MainWindow to be closed
            m_EventHandlerIsRunning = true;

            // Do something async 
            await Task.Delay(1000);
        }
        finally
        {
            // Let MainWindow to be closed
            m_EventHandlerIsRunning = false;
        }
    }
}

但无论如何,您的应用程序必须能够从这种情况(未执行清理代码)中恢复,因为您无法防止随时可能发生的操作系统崩溃或断电。

【讨论】:

  • 感谢您的回答。这似乎是一个可以接受的解决方案。那么我可以说这是必须考虑而不是忽略的事情吗? MSDN 应该在异步文档中提到这一点。
猜你喜欢
  • 2014-06-17
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 2014-02-09
相关资源
最近更新 更多