If you want to see an example of how this dispose vs. finalizer stuff is
implemented, look at the System.IO.FileStream object.
FileStream is the object that you use for reading/writing a file. Now you
could let the GC handle everything for you, and just let the filestream
object go out of scope when you are finished with it. However, you will run
into some problems, and that's where IDisposable comes in.
For example, you might have a situation where you need for your FileStream
to realease a file handle immediately, instead of holding onto it until the
GC decides to collect it. This is the same problem that you would run into
in COM if your COM object held onto a file handle until its refcount went to
zero.
On the filestream object, you would call Dispose() or Close() (which calls
Dispose()) to cause the filestream to release the file handle immediately.
You can implement IDisposable on your own classes to give your developers a
way to indicate that the object should release its resources immediately.
As WhiteWizard mentioned, Dispose is a different beast from a Finalizer
(destructor syntax in C#). You only want a finalizer if your object is
holding onto unmanaged resources, such as a Handle, or a DC.
Here's a good article on how the GC works:
http://msdn.microsoft.com/msdnmag/issues/1100/gci/
Here's a good series on using the GC efficiently:
Using the GC Efficiently Part 1:
http://blogs.msdn.com/maoni/archive/...15/156626.aspx
Using the GC Efficiently Part 2:
http://blogs.msdn.com/maoni/archive/...25/234273.aspx
Using the GC Efficiently Part 3:
http://blogs.msdn.com/maoni/archive/...19/327149.aspx
Using the GC Efficiently Part 4:
http://blogs.msdn.com/maoni/archive/...06/415296.aspx
Clearing up some confusion over finalization:
http://blogs.msdn.com/maoni/archive/...04/252697.aspx
"Volker Hetzer" <vo***********@ieee.org> wrote in message
news:e2**********@nntp.fujitsu-siemens.com...
Hi!
We are thinking of doing some performance intensive parts
of our application in C#.
However, I'm a bit concerned about this GC stuff.
From my time as C++ programmer it was pretty easy to
use heavy objects that for instance contain a database conenction
and I could be sure that when the function ended, the connection
object executed a proper disconnect.
So, given class B, I could
int f()
{
B MyConnection;
...
return 0;
}
int c()
{
f();
//Here the database is closed again.
}
And there was no way I could forget anything.
How does this work with C#?
Is the GC only used with objects that are created with new?
Lots of Greetings!
Volker