是否有可能在c# WPF应用程序- c# 4.0中全局捕获意外错误
我发现DispatcherUnhandledException能够捕获UI线程错误,但实际上我需要TPL线程。UnhandledException能够捕获线程错误,但它仍然会导致软件终止。
因此,任何解决方案都可以捕获线程中未处理的异常,而不是UI线程中的异常,并且仍然让软件运行而不是终止。线程是TPL线程。(任务并行库)
发布于 2011-10-22 20:52:37
将处理DispatcherUnhandledException的一部分添加到您的配置文件中
<configuration>
<runtime>
<legacyUnhandledExceptionPolicy enabled="1"/>
</runtime>
</configuration>这可以防止辅助线程异常关闭应用程序。
发布于 2011-10-23 02:40:06
您可以在第三方物流中使用Custom Escalation Policy来寻址您的case.You,方法是向静态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();
}
}
}https://stackoverflow.com/questions/7859613
复制相似问题