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 - 1 of 1 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. span style="font-style: italic;">// This line of code calls another function of this object, which actually disposes the resources used

  2.         GC.SuppressFinalize(this);    // This line specifies that GC should now ignore this object from its usual garbage collection cycle// Code here for freeing up the resources used by this object, performing checks for it being null or already disposed

  3.     }

  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