We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
Although the .NET Framework takes the memory management task out of your hands, there are still a few things that you must pay attention to when disposing of an object in order for the Garbage Collector to do its work properly.
You would think that once you remove the reference from an object it will eventually be collected by the Garbage Collector, that’s almost true. The fact is that, if that object was registered to an event published by another object, it won’t be collected by the Garbage Collector.
Why you ask? Allow me to explain.
When you register to an event you provide a delegate, and that in fact acts as a reference from the object that published the event to the registering object. So in order to make the GC collect the registering object, you must unsubscribe from all the events. Otherwise there is still a reference to that object in the form of that delegate.
To sum things up, the safest way to ensure that an object will be collected by the GC is to make it inherit IDisposable and in the Dispose method unsubscribe from all the events you were subscribed to.
Subscribe to our feed and get the complete code sample for this article
Tags :.NetDisposeEventFrameworkGarbage CollectorGCIDosposableObjectReference
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd