【发布时间】: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