How can I know if a .net event is already handled?

前端 未结 8 2093

I\'ve written some code to handle an event as follows:

AddHandler myObject.myEvent, AddressOf myFunction

It seemed that everything was work

相关标签:
8条回答
  • 2020-12-31 10:05

    I know this is an old post but just wanted to add a solution for those who come looking in this direction...

    VB.Net creates a special private member variable in the pattern of <YourEvent>Event that you can then use to test against Nothing.

    Public Event MyClick As EventHandler
    
    Private Sub OnMyClick()
        If MyClickEvent IsNot Nothing Then
            RaiseEvent MyClick(Me, New EventArgs())
        Else
            ' No event handler has been set.
            MsgBox("There is no event handler. That makes me sad.")
        End If
    End Sub
    

    Answer sourced from here: Determine if an event has been attached to yet

    0 讨论(0)
  • 2020-12-31 10:06

    Either:

    1. Don't add your handler more than once.

    2. Attempt to remove the handler just prior to adding it.

    0 讨论(0)
  • 2020-12-31 10:07

    Remove the handler and then add it. This way it will never be duplicated. Beware of the null reference error if your object does not exist. I got caught on that too and may happen when you are removing the handler outside the sub where the handler is created.

    if not myObject is nothing then RemoveHandler myObject.myEvent, AddressOf myFunction
    if not myObject is nothing then AddHandler myObject.myEvent, AddressOf myFunction
    
    0 讨论(0)
  • 2020-12-31 10:09

    Assuming it's not your code that's publishing the event, you can't. The idea is that subscribers are isolated from each other - you can't find out about other event subscribers, raise the event yourself etc.

    If the problem is that you're adding your own handler multiple times, you should be able to fix that yourself by keeping track of whether you have added a handler. Steven's idea of removing the handler before adding it is an interesting workaround: it's valid to attempt to remove a handler even when it isn't subscribed. However, I'd regard this as a workaround to your app not really knowing what it should be doing. It's a very quick short-term fix, but I'd be worried about leaving it in for the longer term.

    0 讨论(0)
  • 2020-12-31 10:10

    There's no way to tell that a handler is already attached but you can safely call RemoveHandler on the event before calling AddHandler. If there isn't already a handler, RemoveHandler will have no effect.

    0 讨论(0)
  • 2020-12-31 10:17

    Save your event handler results to the database/session and then read them in again to check if event has already been handled.

    0 讨论(0)
提交回复
热议问题