How can I clear event subscriptions in C#?

前端 未结 10 1798
野趣味
野趣味 2020-11-30 18:43

Take the following C# class:

c1 {
 event EventHandler someEvent;
}

If there are a lot of subscriptions to c1\'s someEven

相关标签:
10条回答
  • 2020-11-30 19:11

    You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods.

    0 讨论(0)
  • 2020-11-30 19:15

    Add a method to c1 that will set 'someEvent' to null.

    public class c1
    {
        event EventHandler someEvent;
        public ResetSubscriptions() => someEvent = null;    
    }
    
    0 讨论(0)
  • 2020-11-30 19:15

    Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events.

    0 讨论(0)
  • 2020-11-30 19:17

    Remove all events, assume the event is an "Action" type:

    Delegate[] dary = TermCheckScore.GetInvocationList();
    
    if ( dary != null )
    {
        foreach ( Delegate del in dary )
        {
            TermCheckScore -= ( Action ) del;
        }
    }
    
    0 讨论(0)
提交回复
热议问题