And*_*son 3 c# wpf error-handling
我有一个 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 { }
}
Run Code Online (Sandbox Code Playgroud)
但是,如果启动一个任务。运行“代码位”并且它抛出一个错误,那么我观察到错误没有被捕获:
Task.Run(() =>
{
throw and error here
});
Run Code Online (Sandbox Code Playgroud)
所以我必须放入“Try-Catch”来捕获它:
Task.Run(() =>
{
try
{
throw an error here
}
catch (Exception ex)
{
do something with error
}
});
Run Code Online (Sandbox Code Playgroud)
~ 这违背了拥有全局错误处理程序的目的
我应该怎么办?
有一个TaskScheduler.UnobservedTaskException事件你可以使用
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.
};
Run Code Online (Sandbox Code Playgroud)
当故障任务的未观察到的异常即将触发异常升级策略时发生,默认情况下,该策略将终止进程。
此应用程序域范围的事件提供了一种机制来防止触发异常升级策略(默认情况下,终止进程)
| 归档时间: |
|
| 查看次数: |
1687 次 |
| 最近记录: |