How do I get deterministic finalization in C#?

In a garbage collected environment, it's impossible to get true determinism. However, a design pattern that we recommend is implementing IDisposable on any class that contains a critical resource. Whenever this class is consumed, it may be placed in a using statement, as shown in the following example:

using(FileStream myFile = File.Open(@"c:temptest.txt",

FileMode.Open))

{

int fileOffset = 0;

while(fileOffset < myFile.Length)

{

Console.Write((char)myFile.ReadByte());

fileOffset++;

}

}

When myFile leaves the lexical scope of the using, its dispose method will be called.

Showing Answers 1 - 0 of 0 Answers

anupamsh

  • Mar 7th, 2012
 

That is true. A class implementing the interface IDisposable can be used in the using statement, something like:

Code
  1. using (MyClass objMyClass = new MyClass())

  2.     {

  3.         objMyClass.DoSomething();

  4.     }

  5.  

  6. This is calling the following code under the hood:

  7.     MyClass objMyClass = new MyClass();

  8.     try {

  9.         objMyClass.DoSomething();

  10.     }

  11.     finally {

  12.         if (objMyClass != null)

  13.             ((IDisposable)objMyClass).Dispose();

  14.     }

  15.  

  16.  

  17. Now when we talk about deterministic disposal and the IDisposable interface, we typically do it in the following manner:

  18.     public void Dispose()

  19.     {

  20.         this.Dispose(true);    // This line of code calls another function of this object, which actually disposes the resources used

  21.         GC.SuppressFinalize(this);    // This line specifies that GC should now ignore this object from its usual garbage collection cycle

  22.     }

  23.            

  24.     protected virtual void Dispose(bool disposing)

  25.     {

  26.         // Code here for freeing up the resources used by this object, performing checks for it being null or already disposed

  27.     }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions