我想为 WinForms 应用程序中任何线程的所有未处理异常设置处理程序方法。我自己不创建任何应用程序域。
根据未处理的异常 https://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx文档,我需要设置UnhandledExceptionMode.ThrowException
模式通过Application.SetUnhandledExceptionMode
也捕获主线程异常的方法:
在使用 Windows 窗体的应用程序中,未处理的异常
主应用程序线程导致 Application.ThreadException 事件
被抚养。如果处理此事件,则默认行为是
未处理的异常不会终止应用程序,尽管
应用程序处于未知状态。在这种情况下,
未引发 UnhandledException 事件。这种行为是可以改变的
通过使用应用程序配置文件,或通过使用
Application.SetUnhandledExceptionMode 方法将模式更改为
ThreadException 事件之前的 UnhandledExceptionMode.ThrowException
处理程序已连接。这仅适用于主应用程序
线。对于未处理的情况会引发 UnhandledException 事件
其他线程中抛出的异常
因此,生成的代码将如下所示:
public static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)
{
// ...
}
[STAThread]
static void Main(string[] args)
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(pathToCheck));
}
可以吗?它会捕获来自任何线程(包括主线程、UI线程和由它创建的所有线程)的所有未处理的异常吗?Task
班级)?我正确理解了文档吗?
是的,我看到了类似的问题this https://stackoverflow.com/questions/5762526/how-can-i-make-something-that-catches-all-unhandled-exceptions-in-a-winforms-a在这里,但我不明白为什么我还应该使用以下代码:
Application.ThreadException += new
ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
您应该订阅这两个事件。请注意,即使这样也不会自动捕获来自其他线程的所有内容。例如,当异步调用委托时,仅当以下情况时,异常才会传播到调用者线程:EndInvoke
叫做。
[STAThread]
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException +=
(sender, args) => HandleUnhandledException(args.ExceptionObject as Exception);
Application.ThreadException +=
(sender, args) => HandleUnhandledException(args.Exception);
}
static void HandleUnhandledException(Exception e)
{
// show report sender and close the app or whatever
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)