我有一个WPF应用程序,可以分成几个线程。我在App.xaml.cs中定义了一个显示详细错误消息的DispatcherUnhandledException事件处理程序,该处理程序在UI线程每次遇到异常时都会被调用。问题出在子线程:它们未处理的异常永远不会得到处理。我该怎么做呢?
示例代码:
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("detailed error message");
}
private void Application_Startup(object sender, StartupEventArgs e)
{
//...
//If an Exception is thrown here, it is handled
//...
Thread[] threads = new Thread[numThreads];
for(int i = 0; i < numThreads; i++)
{
threads[i] = new Thread(doWork);
threads[i].Start();
}
}
private void doWork()
{
//...
//Exception thrown here and is NOT handled
//...
}
编辑:一旦发生未处理的异常,我希望显示带有堆栈跟踪的错误消息,然后退出应用程序。
发布于 2009-09-15 18:00:39
也可以尝试连接到AppDomain.CurrentDomain.UnhandledException事件。
发布于 2009-09-15 18:01:33
根据设计,您应该在DoWork的顶级使用try/catch。一些线程模型迎合了这一点,看看Backgroundworker就是一个例子。
.NET 4任务类为这个问题提供了一个很好的接口。在此之前,您将不得不自己处理它,或者使用BGW或IAsyncResult模型。
https://stackoverflow.com/questions/1428692
复制相似问题