【发布时间】:2018-07-01 14:50:00
【问题描述】:
我阅读了一些其他线程和文章,这些文章表明有一种方法可以捕获源自非 UI 线程的未处理异常。出于某种原因,这对我不起作用。未处理的 UI 异常被捕获。即使我通过在非 UI 线程中抛出异常进行测试,CurrentDomainUnhandledException 也永远不会执行。
更奇怪的是,非 UI 线程上的异常并没有像我想象的那样关闭应用程序。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Application.Current.DispatcherUnhandledException += CurrentDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException +=
CurrentDomainUnhandledException;
}
void CurrentDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
MessageBox.Show(e.Exception.Message, "Caught an unhandled exception!");
}
void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show(ex.Message, "Uncaught Thread Exception",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
我从一个处理插入的设备的事件处理程序中抛出,该设备绝对不是 UI 线程。调试器中断并向我显示异常未处理的消息。但是,当我继续时,应用程序继续运行并且似乎继续工作。我对此感到困惑。
_devicePlugWatcher = new ManagementEventWatcher(pluggedQueryStr);
_devicePlugWatcher.EventArrived += (DevicePluggedEventReceived);
【问题讨论】:
-
您确定没有显示消息框吗?由于调试器将 Visual Studio 带到前台,它可能隐藏在后台。如果您确定,请尝试使用
Dispatcher.[Begin]Invoke打开 UI 线程上的消息框。 -
我在 CurrentDomainUnhandledException 中设置了一个断点,它永远不会被命中。我明白你的意思,如果执行了该代码,那么我可能应该实施该建议。目前处理程序永远不会执行。
-
您确定没有捕获到异常吗?调试器可能会中断第一次机会异常,即使它们后来被捕获。
-
您需要切换回 UI 线程才能显示 MessageBox。工作线程中没有消息循环,因此没有 UI 交互。使用 `CheckAccess' 方法来确定可以在哪里显示消息框或切换到 UI 线程。
-
@Mike,我不明白你的意思。如果我在 CurrentDomainUnhandledException 中设置断点,那么为什么调试器不会在那里中断?