当Sub Main无法访问时,在VB.NET中捕获ThreadingException

我有一个VB.NET
winforms解决方案,并且想添加标准的应用程序异常处理程序–Application.ThreadException和AppDomain.CurrentDomain.UnhandledException.

我有以下代码from MSDN

' Starts the application. '
<SecurityPermission(SecurityAction.Demand, Flags:=SecurityPermissionFlag.ControlAppDomain)> _
Public Shared Sub Main()
    ' Add the event handler for handling UI thread exceptions to the event. '
    AddHandler Application.ThreadException, AddressOf ErrorHandlerForm.Form1_UIThreadException

    ' 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. '
    AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException

    ' Runs the application. '
    Application.Run(New ErrorHandlerForm())
End Sub

当我无法访问Sub Main()方法时,如何在VB.NET中执行此操作?

是否启用了我的解决方案属性的“启用应用程序框架”(Sub Main隐藏)…

最佳答案 我认为你看到了你的问题 – 似乎你错过了代码文件头部的Imports语句.您可以添加所需的导入或完全限定您正在访问的类型:

Imports System
Imports System.Windows.Forms

Public Shared Sub MyApplicationInitialization()
    AddHandler System.Windows.Forms.Application.ThreadException, AddressOf MyThreadExceptionHandler

    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)

    AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionHandler
End Sub

从中可以看出,AppDomain位于System.Windows.Forms命名空间内的System命名空间和Application中.

请注意,您还需要定义自己的事件处理方法,以便在每个AddressOf之后指定.这些可以如下布局:

Sub MyUnhandledExceptionHandler(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
    'your logic here
End Sub

Sub MyThreadExceptionHandler(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs)
    'your logic here
End Sub
点赞