C# Disable Event Handler Problem
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开发者_StackOverflow first time
object.Event -= new System.EventHandler(myHandler);
//my code which doesn't need event handler
object.Event += new System.EventHandler(myHandler);
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?
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.)
精彩评论