Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it necessary to unsubscribe from events?

Tags:

How serious it might be to NOT unsubscribe from the events in c#? Is it mandatory or advisable action?

like image 719
Arseny Avatar asked Jun 03 '10 07:06

Arseny


People also ask

Should I unsubscribe from events c#?

In order to prevent resource leaks, you should 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.

How do I unsubscribe from an event listener?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.

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.

What is an event in C# with example?

Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.


2 Answers

This is the important part from the MSDN documentation that you should take into consideration

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.

like image 170
Pieter Germishuys Avatar answered Sep 20 '22 13:09

Pieter Germishuys


It depends how long the subscriber and publisher live. Here is an in depth article about the problem and several approaches on how to solve it here: Solving the Problem with Events: Weak Event Handlers

like image 35
Giorgi Avatar answered Sep 18 '22 13:09

Giorgi