views:

299

answers:

5

Sometimes I want to attach an event handler but I'm not sure if I've done it already to that object. My workaround is to remove it using -= then add it using += . Is there a better way?

Edit: The reason I want to make sure not to do it twice (or more) is that if I do, it will get fired twice (or more)

A: 

No, there isn't. See http://stackoverflow.com/questions/232863/c-event-handlers

Robert Harvey
+2  A: 

You might want to take a look at this question: http://stackoverflow.com/questions/367523/how-to-ensure-an-event-is-only-subscribed-to-once

julio.g
note the solution there is a major anti-pattern ...
Sam Saffron
+1  A: 

The solution of removing an event and then adding it can blow up in a multithreaded scenario, where you can effectively end up either adding duplicates or exceptioning out.

You can implement add and remove on your event, but that comes with its own caveats.

If you really only need a single cast type action, you can consider just passing an Action around and calling it when needed, this saves on some of the difficult edge cases you get with events.

Sam Saffron
A: 

Did you tried this?

public event MyClickHandler Click = delegate {}; // add empty delegate!

More details checkout : http://stackoverflow.com/questions/9033/hidden-features-of-c

Anuraj
A: 

So, I am assuming you are not in control of the class that raises the event and you can't check it there. If you need run-time checking whether or not you've already registered for an event on the sink side only, you could centralize your registration in a method that checks if you've already signed up, something like ...

private void RegisterForEvent()
{
  lock( _registerLock )
  {
    if( !_iveDoneThisAlready )
    {
      _iveDoneThisAlready = true;
      // register for Event here
    }
  }
}

But, your code would have to agree to that convention. There is nothing forcing a registrant to call this method instead of +=.

JP Alioto