Pages

Thursday, April 23, 2009

Disposing objects in C#

Have you ever been confused of object disposing, when object is garbage collected and what does the Using-block do? Below is a code sample that shows what happends to an object when it loses its references and is garbage collected, and what happends to object after using-block.

Basically, when you use the using block, when the code is done the object's Dispose-method gets called. And you need to implement the IDisposable interface for that. When you're not using the using-block and object gets garbage collected, object's destructor/finalizer gets called.


    1 using System;
    2 
    3 namespace DisposeTest
    4 {
    5   class Tester
    6   {
    7     static void Main(string[] args)
    8     {      
    9       // Note: we create objects in separate method, because if we 
   10       // create instances and call GC in same method, objects would 
   11       // technically still be associated with running code and would 
   12       // therefore not be eligible for garbage collection
   13       InitializeObjects();
   14 
   15       // suggest GC that now would be a lovely time to pick up the trash
   16       GC.Collect();
   17 
   18       Console.ReadLine();
   19     }
   20 
   21     private static void InitializeObjects()
   22     {
   23       // Create an object, and then set its value to null.
   24       // object's Dispose()-method is not called
   25       DisposableObject object1 = new DisposableObject { ObjectID = 1 };
   26       object1 = null;
   27 
   28       // Object's Dispose()-method is called right after we exit the using block
   29       using (DisposableObject object2 = new DisposableObject { ObjectID = 2 })
   30       {
   31 
   32       }      
   33     }
   34   }
   35 }

Here's the class that implements the IDisposable interface, and shows the use of Dispose()-method and destructor.

    1 using System;
    2 
    3 namespace DisposeTest
    4 {
    5   public class DisposableObject : IDisposable
    6   {
    7     public int ObjectID { get; set; }
    8 
    9 
   10     // this method is called when object is disposed, 
   11     // like after using-block
   12     public void Dispose()
   13     {
   14       Console.WriteLine(
   15         "Object {0} says: I've been disposed!", ObjectID);
   16     }
   17 
   18     // this method gets called when object is garbage collected
   19     ~DisposableObject()
   20     {
   21       Console.WriteLine(
   22         "Object {0} says: Argh, garbage collector got me!", ObjectID);
   23     }
   24   }
   25 }


Further reading in MSDN: IDisposable.Dispose Method

No comments:

Post a Comment