如何避免事件被处理两次(如果是相同的处理程序?)
Module Module1
Sub Main()
Dim item As New Item
AddHandler item.TitleChanged, AddressOf Item_TitleChanged
AddHandler item.TitleChanged, AddressOf Item_TitleChanged
item.Title = "asdf"
Stop
End Sub
Private Sub Item_TitleChanged(sender As Object, e As EventArgs)
Console.WriteLine("Title changed!")
End Sub
End Module
Public Class Item
Private m_Title As String
Public Property Title() As String
Get
Return m_Title
End Get
Set(ByVal value As String)
m_Title = value
RaiseEvent TitleChanged(Me, EventArgs.Empty)
End Set
End Property
Public Event TitleChanged As EventHandler
End Class
输出:
Title changed!
Title changed!
期望的输出:
Title changed!
我希望事件管理器检测到此事件已由此处理程序处理,因此不应重新处理(或读取)它。
答案 0 :(得分:6)
您也可以在RemoveHandler
之前随时致电AddHandler
。我在特定场景中发现了这种实用性。
答案 1 :(得分:0)
在HashSet
中包装事件处理程序列表将确保处理程序不是重复引用,问题的Item
类的以下代码段替换将在上面的示例下工作(它不会重复-add处理程序,如果它已经在HashSet
):
Public Class Item
Private m_Title As String
Public Property Title() As String
Get
Return m_Title
End Get
Set(ByVal value As String)
m_Title = value
RaiseEvent TitleChanged(Me, EventArgs.Empty)
End Set
End Property
Private handlers As New HashSet(Of EventHandler)
Public Custom Event TitleChanged As EventHandler
AddHandler(value As EventHandler)
handlers.Add(value)
End AddHandler
RemoveHandler(value As EventHandler)
handlers.Remove(value)
End RemoveHandler
RaiseEvent(sender As Object, e As System.EventArgs)
For Each handler In handlers.Where(Function(h) h IsNot Nothing)
handler(sender, e)
Next
End RaiseEvent
End Event
End Class