IDisposable


Jump to: navigation, search
Exam Prep. Guides
Exam 70-536 Study Guide

1. Types and collections

2. Process, threading,…
3. Embedding features
4. Serialization, I/O
5. .NET Security
6. Interop., reflection,…
7. Global., drawing, text

edit

Contents


The System.IDisposable interface defines a method of releasing unmanaged resources which have been allocated.


Syntax

Declaration syntax

[ComVisibleAttribute(true)] 
public interface IDisposable

Method syntax

The Dispose method performs tasks defined by the application associated with releasing or resetting unmanaged resources. Resources like database connections, handles, files, and streams which are held by an instance of the class implementing this interface.

void Dispose ()


Usage

Although this looks like a simple interface, it brings with it some complications due to digging into Garbage Collector (GC) territory. These complications can be minimized by sticking to these simple rules:

  • Set unmanaged objects to null
  • Call the Dispose methods of managed objects
  • Prevent the Garbage Collector from calling finalize methods on managed objects
class MyClass : IDisposable
{
   FileStream myStream; //large object
 
   public MyClass (string filePath)
   {
      myStream = new FileStream
         (filePath, FileAccess.ReadWrite);
   }
 
   public void Dispose()
   {
      myStream.Dispose();
      //remove myStream from the GC finalize queue
      GC.SuppressFinalize(myStream); 
   }
}

You should only use these classes inside a try-catch-finally statement or a using statement.

using(MyClass testObj = new MyClass("File.txt"))
{
   //use testObj
}
 
//testObj is out of scope here as it has been disposed 

MSDN references


Previous_Page_.gif Next_Page_.gif





Personal tools
Share this page
  • del.icio.us
  • Facebook
  • StumbleUpon