c# - 应该在哪里订阅 AppDomain.UnhandledException?

标签 c# .net wpf

建议的重复是关于DispatcherUnhandledException,而不是AppDomain.CurrentDomain.UnhandledException

原创:

应该在哪里订阅AppDomain.UnhandledExceptionMSDN 上的示例只是在 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/

相关文章:

c# - 访问分配给传入 Func<> 参数的方法

.net - 在 VB.NET 中将十六进制值存储在变量中(Dim xx as "Hex")

DataGrid 中的 WPF 图像绑定(bind)

C#、WPF、Visual Studio 4 : irregular shape color filling

c# - 将 ContextMenu 项的 "IsEnabled"绑定(bind)到按钮

c# - TAP 全局异常处理程序

时间:2019-03-08 标签:c#windowsformscapitalletters

c# - 刷新 ListCollectionView 将 ComboBox 中所选项目的值设置为 null

JavaScript 数学公式编辑器?

c# - 如何发出 GET RESTful 请求