Wednesday, April 6, 2011

C# unhook event

I am using standard windows forms controls under C#.

Short version: is there any problem unhooking a delegate which hasn't been hooked?

Full question:

I have two controls which are different ways of setting a single value. Thus when one is changed, the changed event handler computes a value for the other and sets it. So I need to unhook the change event on the second control temporarily to prevent looping (A changes B, B is changed so it changes A, A is changed...). There are also some other situations where I need to stop the change event. So there are several places where I need to unhook the event, and only one place where it needs to be hooked.

My question is: do I need to keep track of whether the event has been hooked or can I just unhook it as many times as I like and only occasionally hook it again? (Is there any documentation that addresses this?)

From stackoverflow
  • Ya, you can unhook it as many times as you want, no exceptions will be thrown.

  • Unhooking an event handler that was never registered using the -= operator won't give you any problems.

  • This will loop through and unhook any subscribed methods:

    Delegate[] subscribers = myEvent.GetInvocationList();
    
        for(int i = 0; i < subscribers.Length; i++)
    
        {
    
        myEvent -= subscribers[i] as yourDelegateType;
    
        }
    

    However, I think you should be able to avoid the looping problem by writing a single handler with logic to determine how the data should be modified. This would be cleaner and more maintainable.

    JMD : I was about to post something similar regarding a more maintainable solution. In particular, I wouldn't like to be the developer who comes along later to maintain code that assigns and removes handlers instead of using a flag, or a single handler.

0 comments:

Post a Comment