当前位置 : 主页 > 编程语言 > c语言 >

.net – ThreadException只能有1个AND ONLY处理程序吗?

来源:互联网 收集:自由互联 发布时间:2021-06-24
我不明白为什么在VS2010中运行(CTRL-F5 – Run Without Debugger)时,我在以下情况下只得到1个Message Box: Public Class Form1 Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load ' Ad
我不明白为什么在VS2010中运行(CTRL-F5 – Run Without Debugger)时,我在以下情况下只得到1个Message Box:

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        ' Add the event handler for handling UI thread exceptions to the event.
        AddHandler Application.ThreadException, AddressOf ThreadExceptionHandler
        AddHandler Application.ThreadException, AddressOf ThreadExceptionHandler2

        Throw New Exception("Ha!")

    End Sub

    Private Sub ThreadExceptionHandler(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs)
        MsgBox("FirstHandler")
    End Sub

    Private Sub ThreadExceptionHandler2(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs)
        MsgBox("SecondHandler")
    End Sub
End Class
呵呵.显然是这样.

根据dotPeek,这是Application.ThreadException的添加和删除处理程序的代码:

public static event ThreadExceptionEventHandler ThreadException
{
  add
  {
    System.Windows.Forms.IntSecurity.AffectThreadBehavior.Demand();
    Application.ThreadContext threadContext =
      Application.ThreadContext.FromCurrent();
    lock (threadContext)
      threadContext.threadExceptionHandler = value;
  }
  remove
  {
    Application.ThreadContext threadContext =
      Application.ThreadContext.FromCurrent();
    lock (threadContext)
      threadContext.threadExceptionHandler -= value;
  }
}

请注意,在remove处理程序中,它如何使用 – =按预期方式,但在add处理程序中,它只使用=?你认为应该是=,但它看起来不是.

所以是的,当你使用=运算符添加一个新的事件处理程序(转换为对add处理程序的调用)时,WinForms实际上是替换现有的处理程序而不是添加它.

看起来像一个简单明了的bug.如果您在Connect上写这个,请在​​此处发布链接,以便其他人可以投票.

网友评论