Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to unsubscribe from (manually subscribed to) events in asp.net?

Do the same best practis rules regarding subscribing/unsubscribing to events apply in asp.net?

I know it might seem like a silly question, but when I think about it, I have never really seen any code where people first subscribe to an event on a page and then unsubscribe later on in the web request.

Example 1: On a page, in the Page_Load method, I subscribe to a updating event on a ListView. Should I unsubscribe from that event later on, for example in the OnPreRenderComplete method?

Example 2: In the passive view patter, a view (Page control/Usercontrol) will raise an event whenever it needs the presenter to do anything. So the presenter needs to subscribe to events on the view, but do it also need to unsubscribe from the events again?

Best regards, Egil.

like image 507
Egil Hansen Avatar asked Dec 05 '08 21:12

Egil Hansen


People also ask

Do I need to 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.

Which of the following operator is used to unsubscribe any method from delegate reference?

The signature of the handler method must match the delegate signature. Register with an event using the += operator. Unsubscribe it using the -= operator.


2 Answers

The page instance and all of its components will "go out of scope" when request completes, e.g. they become eligible for GC. So your ListView will go out of scope along with the Page/user controls on it. You don't need to unsubscribe (unless you subscribe to an event that belongs to some kind of singleton that survives every request and use one of the methods of the page as the event handler, for example).

The same thing is valid for the presenter (again as long as this presenter is used solely with one page and goes out of scope after that).

like image 140
liggett78 Avatar answered Oct 30 '22 20:10

liggett78


Generally, no. Events are supposed to be dumped automatically when the page unloads. SUPPOSED to be. I've run into a bug before (in .NET 1.1) where that wasn't the case.

I won't bother unsubscribing, unless I notice a problem with the page (like, a method being called 20 times from a phantom in the call stack: that's usually a sign of something not being unsubscribed properly).

like image 40
TheSmurf Avatar answered Oct 30 '22 20:10

TheSmurf