Does assigning null remove all event handlers from

2019-02-02 21:00发布

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 -=?

4条回答
孤傲高冷的网名
2楼-- · 2019-02-02 21:39

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.

查看更多
Lonely孤独者°
3楼-- · 2019-02-02 21:48

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

查看更多
三岁会撩人
4楼-- · 2019-02-02 21:50

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.

查看更多
Anthone
5楼-- · 2019-02-02 21:57

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;
    }
}
查看更多
登录 后发表回答