在 WPF 中捕获子线程中未处理的异常
我有一个可以分离多个线程的 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
//...
}
编辑: 一旦发生未处理的异常,我想显示带有堆栈跟踪的错误消息,然后退出应用程序。
I have a WPF application that spins off several threads. I have defined a DispatcherUnhandledException event handler in App.xaml.cs that displays a detailed error message, and this handler gets called every time the UI thread encounters an exception. The problem is with the child threads: their unhandled exceptions never get handled. How do I do this?
Sample code:
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
//...
}
Edit: Once an unhandled exception occurs, I want to display an error message with a stack trace, and then exit the application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试连接到 AppDomain.CurrentDomain.UnhandledException 事件以及。
Try hooking up to the AppDomain.CurrentDomain.UnhandledException event as well.
这是设计使然,您应该在 DoWork 的顶层使用 try/catch。一些线程模型可以满足这一点,请查看Backgroundworker 的示例。
.NET 4 Task 类为这个问题提供了一个很好的接口。在那之前,您必须自己处理它,或者使用 BGW 或 IAsyncResult 模型。
This is by design, you should use a try/catch at the top-level of DoWork. Some threading models cater for this, take a look at the Backgroundworker for an example.
The .NET 4 Task class provides a nice interface to this problem. Until then, you will have to take care of it yourself, or use the BGW or IAsyncResult models.