Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 捕获WPF中子线程中未处理的异常_C#_Wpf_Multithreading_Exception Handling_Unhandled Exception - Fatal编程技术网

C# 捕获WPF中子线程中未处理的异常

C# 捕获WPF中子线程中未处理的异常,c#,wpf,multithreading,exception-handling,unhandled-exception,C#,Wpf,Multithreading,Exception Handling,Unhandled Exception,我有一个WPF应用程序,它派生出几个线程。我在App.xaml.cs中定义了一个DispatcherUnhandledException事件处理程序,它显示详细的错误消息,并且每当UI线程遇到异常时都会调用该处理程序。问题在于子线程:它们未处理的异常永远不会得到处理。我该怎么做 示例代码: private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.Dispatcher

我有一个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
    //...
}
私有无效应用程序\u DispatcherUnhandledException(对象发送方,System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(“详细错误消息”);
}
私有void应用程序\u启动(对象发送方、StartupEventArgs e)
{
//...
//如果在此处引发异常,则会对其进行处理
//...
线程[]线程=新线程[numThreads];
for(int i=0;i

编辑:一旦发生未处理的异常,我想显示一条带有堆栈跟踪的错误消息,然后退出应用程序。

尝试连接到事件。

这是出于设计,您应该在DoWork的顶层使用Try/catch。一些线程模型满足这一要求,以Backgroundworker为例


NET4任务类为这个问题提供了一个很好的接口。在此之前,您必须自己处理,或者使用BGW或IAsyncResult模型。

请参阅,了解为什么在退出之前只应使用此记录错误。@Henk,这是我已经发布的相同链接。不过你是对的,异常应该只用于日志记录目的。Brandon,好的,我没有检查你的链接(-:但是每个线程都应该处理自己的异常。这是一个非常有效的答案,但对于我的特殊情况,我碰巧在doWork()中运行了一个长而复杂的进程.据我所知,try/catch块会造成相当不错的性能损失,我更喜欢在小块代码上使用它们。不,try/catch只会在引发异常时影响性能,而速度通常不是最大的问题。在正常情况下没有缺点。在异常从线程“转义”后,你的整个应用程序的稳定性有问题。