VB.NET如何使用ApplicationEvents来捕获线程中的异常?

时间:2015-04-25 18:58:10

标签: vb.net error-handling

我的ApplicationEvents.vb中有一段代码可以处理所有异常:

Namespace My

' The following events are available for MyApplication:
' 
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication

    Private Delegate Sub SafeApplicationThreadException(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)

    Private Sub ShowDebugOutput(ByVal ex As Exception)

        Dim frmD As New frmDebug()
        frmD.rtfError.AppendText(ex.ToString())
        frmD.ShowDialog()

        Environment.Exit(0)

    End Sub

    Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup

        System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic)

        AddHandler System.Windows.Forms.Application.ThreadException, AddressOf app_ThreadException


        AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf AppDomain_UnhandledException
    End Sub

    Private Sub app_ThreadException(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)


        If MainForm.InvokeRequired Then

            MainForm.Invoke(New SafeApplicationThreadException(AddressOf app_ThreadException), New Object() {sender, e})
        Else
            ShowDebugOutput(e.Exception)
        End If

    End Sub

    Private Sub AppDomain_UnhandledException(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)

        ShowDebugOutput(DirectCast(e.ExceptionObject, Exception))

    End Sub

    Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException

        ShowDebugOutput(e.Exception)

    End Sub

End Class


End Namespace

但是,我发现它不会从内部捕获例外,例如BGWorker_DoWork子。

但是,它将捕获同一BGWorker_RunWorkerCompleted子上的异常。

我有没有办法从线程中捕获异常,而不使用Try-Catch?

0 个答案:

没有答案