I am using C# language and I know that when I include destructors in my classes they are called automatically during the guarbage collection process.
but I don't understand the benefit of implementing the IDisposable?and if the Dispose() method is automatically called or I should call it only manually?and what is the relation of these two methods (destructor and dispose()) with object.finalize()?
thanks in advance.
Loading
Kirtan PatelPosted Oct 17, 2009, 3:10 PM
There are situations when you might need to allocate memory for unmanaged resources from managed code. As an example, suppose you have to open a database connection from within a class. The database connection instance is an unmanaged resource encapsulated within this class and should be released as soon as you are done with it. In such cases, you'll need to free the memory occupied by the unmanaged resources explicitly, because the GC doesn't free them implicitly.
Briefly, the GC works as shown below:
- It searches for managed objects that are referenced in managed code.
- It then attempts to finalize those objects that are not referenced in the code.
- Lastly, it frees the unreferenced objects and reclaims the memory occupied by them.
The GC maintains lists of managed objects arranged in "generations." A generation is a measure of the relative lifetime of the objects in memory. The generation number indicates to which generation an object belongs. Recently created objects are stored in lower generations compared to those created earlier in the application's life cycle. Longer-lived objects get promoted to higher generations. Because applications tend to create many short-lived objects compared to relatively few long-lived objects, the GC runs much more frequently to clean up objects in the lower generations than in the higher ones.Roei BarPosted Oct 17, 2009, 3:00 PM
meaning that the GC will not handle them until the application ends, which will make your application very heavy on memory load, from objects that are not realy in use
you should read the following :
http://weblogs.asp.net/pwilson/archive/2004/02/20/77435.aspx
http://blogs.msdn.com/kimhamil/archive/2008/11/05/when-to-call-dispose.aspx
hope this answers your question