views:

64

answers:

2

i am using textchanged event and i disable it where i don't need as following

object.Event -= new System.EventHandler(myHandler);
//my code which doesn't need event handler
object.Event += new System.EventHandler(myHandler);

i used many times like this. but i needed sometimes 2 disable code like this:

object.Event -= new System.EventHandler(myHandler);
object.Event -= new System.EventHandler(myHandler);

of course i finished it with 2 enable code

object.Event += new System.EventHandler(myHandler);
object.Event += new System.EventHandler(myHandler);

i don't know yet why i needed 2 times remove event handler but it worked great.

but in 1 case i got problem.

it doesn't work with 2 or more disable code.

my question is, how can i watch this eventhandler if it needs just one -= code or more? or how can i manage it? i always worked like this, to make sure that i always leave event handler as first time

object.Event -= new System.EventHandler(myHandler);
//my code which doesn't need event handler
object.Event += new System.EventHandler(myHandler);
A: 

You need to remove an event handler as many times as you've added it - and you won't be able to tell when that is, as the subscriptions are effectively hidden from you.

Ideally, just make sure you only subscribe as many times as you need to, and it should be obvious how many times you need to unsubscribe too. Usually this will be once. It's somewhat odd that you ended up with two subscriptions to start with... I suspect that may indicate a bug somewhere in your code.

Note that unsubscribing using an event handler which isn't already subscribed is a no-op.

(Will's idea of the event handler itself knowing whether or not it's really "active" is a good one too, btw.)

Jon Skeet
+4  A: 

My advice would be to stop removing and re-adding the event handler, and instead add a flag to your event handler itself which inhibits whatever activities you need to inhibit during these sections of code.

You can either have a single boolean flag, or use some kind of reference count, depending on how you need to cope with nesting.

If there's some reason why you can't change the existing event handler, what about creating a new event hander which you attach to Event, and call the old one from that?

Will Dean
yes it's more efficient than enable and disable handler
Space Cracker
i have done it and it works great. Thanks a lot
bilal
Excellent! Glad it helps. You're new here - don't forget to vote up stuff you like or answers you accept
Will Dean