views:

61

answers:

1

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?

+5  A: 

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.

Mitch Wheat
Correct. As long as there's no strong reference to the object itself, the object will be GCed and the event handlers automatically unsubscribed. MSDN isn't very clear on this...
Noldorin
@Noldorin: yeah, I always have to think twice about it!
Mitch Wheat