Clearing subscriptions: What will break this self-

2019-08-24 17:43发布

I've been studying garbage collection and event handlers, and in my studies, I came across some code that appears to clean all subscriptions, anonymous or otherwise, from an event handler. The code is as follows:

public event CustomEventHandler customHandler;

...    
///Something somewhere subscribes to the customHandler
...

///Method used for cleanup
void ClearSubscriptions(CustomEventHandler handler){
     if(handler == null){return;}

     Delegate[] delegates = handler.GetInvocationList();
     foreach(Delegate item in delegates){
         handler -= (CustomEventHandler)item;
     }
}

...

///And in the Dispose method
ClearSubscriptions(customHandler);

Unfortunately, I couldn't find the original answer that had this code, so I can't properly give credit (feel free to edit if anyone knows where to find it).

Now, my understanding of this is that it seems to take the event handler and remove all subscriptions to it, anonymous or otherwise, freeing it up for garbage collection. Particularly, putting this code in a Dispose method seems like a failsafe way to make sure that this handler will not cause a memory leak.

So my question is, assuming that the Dispose method will call this ClearSubscriptions method, what situations will break the ClearSubscriptions method and cause it to work in a way other than what I expect?

0条回答
登录 后发表回答