Skip to main content
gamedev.net
🔒 Locked

[.net] Disposing objects?

Started by adammil2000 1 reply 500+ views
Original Post
adammil2000
adammil2000
I read about the "using" statement, but if .NET automatically garbage collects, then can someone give an example why to use "using"? Also, I was wondering the same thing about a Finalizer. Thanks!
itachi
itachi
A genereal rule is: acquire late, release early. If you don't call dispose on disposable objects you rely on the garbage collector to clean up your resources and you never know for sure when that is going to happen. That can be a real problem for certain resources, like DB-Connections. Any object that has fields that are disposable, should implement IDisposable themselves, and if you don't call Dispose on them there might be unneeded object graphs that don't get destroyed.

The main advantage of the using syntax is that it calls Dispose in a finally block, so it's called whether or not there was an Exception.

This also allows for more "creative" uses of the using syntax. For example, in my unit tests I have a small helper class that implements IDisposable: it opens a Transaction when it's created and rolls back the transaction when it's disposed.

So I can use
[Test]public void TestStuff() {  using (Transaction.RollBack) {    //do stuff  }}

instead of
[Test]public void TestStuff() {  Transaction t = new Transaction();  try {    //do stuff  }  finally {    t.RollBack();  } }

which is much nicer to read and type.

There are some interesting articles about the Garbage Collector on MSDN, this is a good one if I remember correctly:
http://msdn.microsoft.com/msdnmag/issues/1100/GCI/default.aspx
ernow
ernow
Yes, do read the MSDN article on this and remember that Dispose has little to do with the garbage collector but is just a way of providing a standard way of letting an object free its claimed resources (EXCLUDED its own memory!) such as managed resources (e.g. SqlConnection, streams) and unmanaged resources (any API that claims memory that is NOT collected by the garbage collector)

Dispose can becalled from outside the object (when the client doesn't need the managed and unmanaged resources anymore) or from within (during destruction/finalization when the client doesn't need the unmanaged resources anymore) You cannot release managed resources during finalization because the managed resources might have been mark unreachable and have been finalized before)

cheers

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.