Does assigning null remove all event handlers from

2019-02-02 21:50发布

问题:

I have defined new member in my class

protected COMObject.Call call_ = null;

This class has the following event handler that I subscribed to

call_.Destructed += new COMObject.DestructedEventHandler(CallDestructedEvent);

Will setting my member to null as following remove the event handler?

call_ = null;

or I have to unsubscribed with -=?

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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