Clearing subscriptions: What will break this self-cleaning event publisher?

烈酒焚心 提交于 2019-12-13 03:29:52

问题


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?

来源:https://stackoverflow.com/questions/52745233/clearing-subscriptions-what-will-break-this-self-cleaning-event-publisher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!