Avoid duplicate event handlers?

How to avoid the event being executed twice (if it is the same handler?)

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

Conclusion:

Title changed!
Title changed!

Required Conclusion:

Title changed!

I want the event manager to detect that this handler has already been processed by this handler, and therefore it should not process (or read) it.

+3
source share
2 answers

Purchasing a list of event handlers in HashSetensures that the handlers will not duplicate links, the next fragment replacement for the question class Itemwill work according to the above pattern (it will not re-add the handler if it is already in 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
0
source

RemoveHandler AddHandler. .

+6

All Articles