Does assigning null remove all event handlers from an object?

后端 未结 4 566
终归单人心
终归单人心 2020-12-29 02:33

I have defined new member in my class

protected COMObject.Call call_ = null;

This class has the following event handler that I subscribed t

相关标签:
4条回答
  • 2020-12-29 03:08

    yes, you should use overloaded -= to unsubscribe an event.

    simply assigning a reference to null will not do that automatically. The object will still be listening to that event.

    0 讨论(0)
  • 2020-12-29 03:13

    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)
  • 2020-12-29 03:21

    You must use the subtraction assignment operator (-=) to unsubscribe from an event. Only after all subscribers have unsubscribed from an event, the event instance in the publisher class is set to null.

    0 讨论(0)
  • 2020-12-29 03:24

    You should always unsubscribe your event handlers by -= before setting to null or disposing your objects (simply setting variable to null will not unsubscribe all of the handlers), as given in the MSDN excerpt below:

    To prevent your event handler from being invoked when the event is raised, simply unsubscribe from the event. In order to prevent resource leaks, it is important to unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, your subscriber object will not be garbage collected.

    explained at the below link in the Unsubscribing section:

    How to: Subscribe to and Unsubscribe from Events (C# Programming Guide)

    More information at:

    Why you should always unscubscribe event handlers

    0 讨论(0)
提交回复
热议问题