-4

I am trying to unregister the event handler at the end of my program. It looks like this -

myobject.EventHandler -= new MyEventHandler(MyMethod);

Now, I noticed that under certain conditions this statement gets executed multiple times. The program seems to work as expected but I want to confirm that it is not doing something weird.

When the handler is unregistered the first time object.EventHandler is set to NULL. So is it ok to execute this statement any number of times?

Thanks

Fox
  • 9,384
  • 13
  • 42
  • 63
  • 4
    I think you're asking the wrong question here. Your program executes something multiple times while it should only execute once. Wouldn't it be better to figure out why it behaves like this and solve that instead? – Matthijs Sep 06 '14 at 13:11
  • 1
    "at the end of my program" you shouldn't need to unsubscribe anything. – H H Sep 06 '14 at 13:13

2 Answers2

1

When the handler is unregistered the first time object.EventHandler is set to NULL. So is it ok to execute this statement any number of times?

Yes, it's all right. It just won't do anything.

By the way, you don't need to explicitly create the delegate, you can just do this:

myobject.EventHandler -= MyMethod;

(unless you're still using C# 1, which seems unlikely in 2014...)

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
1

I agree with the comments that you should look into why the code is executed multiple times whereas it should be executed just once and especially since how many times it is executed varies (according to your description).

I guess this is from asp.net? If so, you need to be careful with autopostback property on some controls which, when firing some events, could trigger parent control events. The reason why I am guessing this if from asp.net is because you said 'sometimes' hence when the control like button or textbox is not used it may behave 'normal'. Though this is just pure guessing as your question is lack of details...

dragonfly02
  • 3,403
  • 32
  • 55