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 -=?
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.
By default most event handlers return void, however, it is possible for handlers to return values.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With