1

Possible Duplicate:
How to ensure an event is only subscribed to once

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)

Community
  • 1
  • 1
JoelFan
  • 37,465
  • 35
  • 132
  • 205
  • 7
    My advice: become sure. Why are you in a situation where you don't know the state of your own program? – Eric Lippert Jul 07 '09 at 02:11
  • 2
    Don't get me wrong, but you have a bigger problem on your hand than making sure there is only one event handler. I mean, if it's your own code, how would you NOT know that you have already added an event handler? – SolutionYogi Jul 07 '09 at 02:13

3 Answers3

1

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.

Community
  • 1
  • 1
Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
0

Did you try this:

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

More details checkout: Hidden Features of C#?

Community
  • 1
  • 1
Anuraj
  • 18,859
  • 7
  • 53
  • 79
0

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
  • 44,864
  • 6
  • 88
  • 112