我想为我的WinForms应用程序中任何线程的所有未处理异常设置处理程序方法。我不自己创建任何应用程序域。
根据UnhandledException文档,我需要通过Application.SetUnhandledExceptionMode
方法设置UnhandledExceptionMode.ThrowException
模式,以捕获主线程的异常:
在使用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
类创建的所有线程)的所有未处理异常吗?我正确地理解了这些文件吗?
是的,我在这里看到了像这这样的问题,但我不明白为什么还要使用以下代码:
Application.ThreadException += new
ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
发布于 2015-09-04 02:49:15
你应该订阅这两个事件。请注意,即使这样,也不会自动捕获来自其他线程的所有内容。例如,在异步调用委托时,只有在调用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
}
https://stackoverflow.com/questions/32394179
复制