是否可以在 c# WPF 应用程序中全局捕获意外错误 - c# 4.0
我发现 DispatcherUnhandledException 能够捕获 UI 线程错误,但实际上我需要 TPL 线程。UnhandledException 能够捕获线程错误,但它仍然导致软件终止。
因此,任何解决方案都可以在不在 UI 线程中的线程中捕获未处理的异常,并且仍然让软件运行不会终止。线程是 TPL 线程。(任务并行库)
是否可以在 c# WPF 应用程序中全局捕获意外错误 - c# 4.0
我发现 DispatcherUnhandledException 能够捕获 UI 线程错误,但实际上我需要 TPL 线程。UnhandledException 能够捕获线程错误,但它仍然导致软件终止。
因此,任何解决方案都可以在不在 UI 线程中的线程中捕获未处理的异常,并且仍然让软件运行不会终止。线程是 TPL 线程。(任务并行库)
DispatcherUnhandledException
您已经完成的处理的一部分将其添加到您的配置文件中
<configuration>
<runtime>
<legacyUnhandledExceptionPolicy enabled="1"/>
</runtime>
</configuration>
这可以防止您的辅助线程异常关闭应用程序。
您可以Custom Escalation Policy
在 TPL 中使用来解决您的问题。您可以通过向静态System.Threading.Tasks.TaskScheduler.UnobservedTaskException
成员添加事件处理程序来完成此操作
class Test
{
static void Main(string[] args)
{
// create the new escalation policy
TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) =>
{
// mark the exception as being handled
eventArgs.SetObserved();
// get the aggregate exception and process the contents
((AggregateException)eventArgs.Exception).Handle(ex =>
{
// write the type of the exception to the console
Console.WriteLine("Exception type: {0}", ex.GetType());
return true;
});
};
// create tasks that will throw an exception
Task task1 = new Task(() =>
{
throw new NullReferenceException();
});
Task task2 = new Task(() =>
{
throw new ArgumentOutOfRangeException();
});
// start the tasks
task1.Start(); task2.Start();
// wait for the tasks to complete - but do so
// without calling any of the trigger members
// so that the exceptions remain unhandled
while (!task1.IsCompleted || !task2.IsCompleted)
{
Thread.Sleep(500);
}
// wait for input before exiting
Console.WriteLine("Press enter to finish and finalize tasks");
Console.ReadLine();
}
}
}