在多线程环境中使用AppDomain.UnhandledException

时间:2015-12-28 08:56:56

标签: c# multithreading exception-handling

我想检查是否有可能在同一个地方捕获所有无法处理的异常。

我看到有AppDomain.UnhandledException

我用过这样的话:

public void MainMethod()
{
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

    new Thread()...
}

static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
    Exception e = (Exception)args.ExceptionObject;
    LogFile.Log("MyHandler caught : " + e.Message);
}

当主线程中发生未处理的异常时,它会起作用,但是在内部线程中它不会捕获它。

是否有可能从同一个地方的所有线程中捕获异常,或者我必须将它包装在每个线程上吗?

1 个答案:

答案 0 :(得分:0)

我们使用这种方法,尝试一下:

    private static void SetupExceptionHandling()
    {
        // Add the event handler for handling UI thread exceptions to the event.
        Application.ThreadException += ApplicationThreadException;

        // Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

        // Add the event handler for handling non-UI thread exceptions to the event.
        AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;

        //  This AppDomain-wide event provides a mechanism to prevent exception escalation policy (which, by default, terminates the process) from triggering.
        //  Each handler is passed a UnobservedTaskExceptionEventArgs instance, which may be used to examine the exception and to mark it as observed.
        TaskScheduler.UnobservedTaskException += TaskSchedulerUnobservedTaskException;

        // Add the event handler for handling UI thread exceptions to the event.
        Dispatcher.CurrentDispatcher.UnhandledException += DispatcherUnhandledException;
    }