【问题标题】:Global Error Handling in Task.Run for realtime User ntoficationTask.Run 中的全局错误处理实时用户通知
【发布时间】:2016-01-12 05:00:22
【问题描述】:

我有一个 wpf c# 应用程序。

我通常使用全局错误处理程序来捕获所有错误:

private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    try
    {
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => Xceed.Wpf.Toolkit.MessageBox.Show(e.Exception.ToString(), "Error",
          MessageBoxButton.OK, MessageBoxImage.Error)));
        e.Handled = true;
        InformedWorkerDataService.Common.Shared.RecordMessage(e.Exception.ToString(), true);
    }
    finally { }
}

但是,如果启动一个 task.run 'bit of code' 并且它抛出一个错误,那么我观察到错误没有被捕获:

Task.Run(() =>
{
    throw and error here    
});

所以我必须放入一个“Try-Catch”的东西来捕捉它:

Task.Run(() =>
{
    try
    {
        throw an error here
    }
    catch (Exception ex)
    {
        do  something with error
    }
});

~ 破坏了拥有全局错误处理程序的对象 但是,如果我使用这种方法:

TaskScheduler.UnobservedTaskException += (s, e) => {
    e.Exception  //The Exception that went unobserved.
    e.SetObserved(); //Marks the Exception as "observed," thus preventing it from triggering exception escalation policy which, by default, terminates the process.
};

...它将执行我的全局异常处理,但如果我想实时通知用户错误,它不会做得很好,因为它在一个单独的线程上。

什么是好的妥协?

【问题讨论】:

    标签: wpf error-handling task


    【解决方案1】:

    不幸的是,TaskScheduler.UnobservedTaskException 不能保证实时触发,但会抛出异常。这意味着使用此处理程序进行用户通知可能会非常混乱,因为用户操作和错误通知不会同步发生。对于“意外”任务异常的用户驱动处理,您可以创建如下帮助方法并使用TaskEx.Run 而不是Task.Run

    public static class TaskEx
    {
        public static Task Run(Action function)
        {
            return Task.Run(() =>
            {
                try
                {
                    function();
                }
                catch (Exception ex)
                {
                    TraceEx.TraceException(ex);
                    //Dispatch your MessageBox etc.
                }
            });
        }
    }
    

    显然,这并不像添加全局处理程序那么简单(仍应出于跟踪目的进行),但在 UI 驱动的代码中实现起来却足够简单。

    【讨论】:

      猜你喜欢
      • 2016-04-08
      • 2019-02-03
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      相关资源
      最近更新 更多