ThreadException 只能有 1 个且只有 1 个处理程序吗? [英] Can there only be 1 AND ONLY 1 handler for ThreadException?

查看:21
本文介绍了ThreadException 只能有 1 个且只有 1 个处理程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么在 VS2010 中使用 (CTRL-F5 - Run without Debugger) 在以下情况下只得到 1 个消息框:

I don't understand why I only get 1 Message Box in the following case when I run using (CTRL-F5 - Run Without Debugger) in VS2010:

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,这里是 add 和 <代码>删除 Application.ThreadException 的处理程序:

According to dotPeek, here's the code for the add and remove handlers for 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 处理程序中,它只使用 =?你会认为应该是 +=,但它看起来不是.

Notice how, in the remove handler, it uses -= as expected, but in the add handler, it just uses =? You'd think that should be +=, but it looks like it is not.

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

So yes, when you use the += operator to add a new event handler (which translates to a call to the add handler), WinForms is actually replacing the existing handler instead of adding to it.

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

Looks like a bug, plain and simple. If you write this up on Connect, post a link here so others can vote for it.

这篇关于ThreadException 只能有 1 个且只有 1 个处理程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆