views:

89

answers:

4

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

AddHandler myObject.myEvent, AddressOf myFunction

It seemed that everything was working at first, but when I ran the debugger, I discovered that oftentimes, myFunction would run several times each time myObject.myEvent fired. I figured out that I had allowed the code to add the event handler to run more than once, resulting in this behavior.

Is there a way I can do something like this?

If myObject.myEvent is not handled Then
  AddHandler myObject.myEvent, AddressOf myFunction
End If
+6  A: 

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.

Jon Skeet
"Doc, it hurts when I do this." "So don't do this."
Steven Sudit
You're right about it being kind of a hack, especially since leaving your event hooked can effectively cause a memory leak.
Steven Sudit
+4  A: 

Either:

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

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

Steven Sudit
A: 

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

Kon
+1  A: 

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.

Josh Einstein