代码之家  ›  专栏  ›  技术社区  ›  MrSpudtastic

清除订阅:什么将破坏此自清理事件发布服务器?

  •  0
  • MrSpudtastic  · 技术社区  · 7 年前

    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);
    

    不幸的是,我找不到包含这段代码的原始答案,所以我不能正确地给出答案(如果有人知道在哪里可以找到它,请随意编辑)。

    现在,我对这一点的理解是,它似乎接受了事件处理程序并删除了对它的所有订阅(匿名或其他),从而将其释放出来进行垃圾收集。特别是,将此代码放在Dispose方法中似乎是确保此处理程序不会导致内存泄漏的一种故障保护方法。

    所以我的问题是,假设Dispose方法将调用这个ClearSubscriptions方法,什么情况会破坏ClearSubscriptions方法并导致它以我期望的方式工作?

    0 回复  |  直到 7 年前