建议的重复是关于DispatcherUnhandledException
,而不是AppDomain.CurrentDomain.UnhandledException
。
原创:
应该在哪里订阅AppDomain.UnhandledException
? MSDN 上的示例只是在 Main
中显示它,这是我在 Winforms 中所做的:我在 Program.Main 中订阅它:
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
但是我在隐藏了 Main
的 WPF 中找不到合适的位置。我搜索过,但主要是找到关于是否订阅它的讨论,假设读者现在会去哪里。
最佳答案
假设您在 Visual Studio 中使用默认模板创建了项目,您应该有一个名为 app.xaml
的文件,在它下面还有另一个名为 app.xaml.cs
的文件.
在 App
类中,您可以将其添加到 OnStartup
的开头(连同 Dispatcher.UnhandledException
):
protected override void OnStartup(StartupEventArgs e)
{
// don't forget to call base implementation
base.OnStartup(e);
Dispatcher.UnhandledException += Dispatcher_UnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
实际上,Dispatcher.UnhandledException
在大多数情况下应该足够了。这意味着您可以完全跳过使用 AppDomain.CurrentDomain.UnhandledException
。还注册到 AppDomain.CurrentDomain.UnhandledException
的唯一原因是在主 UI 线程以外的线程中引发异常。但我认为更好的做法是在各自的线程中实际捕获这些异常。
关于c# - 应该在哪里订阅 AppDomain.UnhandledException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30325017/