Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does assigning null remove all event handlers from an object?

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

like image 225
Dor Cohen Avatar asked Jan 17 '12 09:01

Dor Cohen


People also ask

Is an EventHandler a delegate?

The EventHandler delegate is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must use the generic EventHandler<TEventArgs> delegate class.

What is generally the return type of event handlers?

By default most event handlers return void, however, it is possible for handlers to return values.

What are event handlers?

In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.


2 Answers

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.

like image 195
Azodious Avatar answered Sep 19 '22 22:09

Azodious


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

like image 39
VSS Avatar answered Sep 17 '22 22:09

VSS