Does assigning null remove all event handlers from an object?

[亡魂溺海] 提交于 2019-12-18 11:41:47

问题


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


来源:https://stackoverflow.com/questions/8892579/does-assigning-null-remove-all-event-handlers-from-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!