Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to manually remove all event to make my object remove from memory?

I have read in MSDN that is require to Unsubscribing every events an object has to be able to dispose it from memory. I always used -= to remove all references to event inside my object (like MSDN show).

Now, I have to maintain code and it has some memory leak on it. I see that the previous developer simply set the object that has all events subscribes on it to NULL and do not -= every event method.

Example:

_watcher.Changed += new ...
_watcher.Created += new ...
_watcher.Deleted += ..

//later.

_watcher = NULL;

Is it a good way or does it keeps the variable in memory?

like image 337
Patrick Desjardins Avatar asked Dec 02 '25 03:12

Patrick Desjardins


1 Answers

If there are no other references to _watcher, then there is no need to remove the event handlers to avoid a memory leak.

As a matter of habit I tend to explicitly remove event handlers.

like image 148
Mitch Wheat Avatar answered Dec 04 '25 19:12

Mitch Wheat