微软自带的注释摘要

// 摘要: 

    //     定义一种释放分配的资源的方法。

    [ComVisible(true)]

    public interface IDisposable

    {

        // 摘要: 

        //     执行与释放或重置非托管资源相关的应用程序定义的任务。

        void Dispose();

    }


此接口的主要用途是释放非托管资源。 当不再使用托管对象时,垃圾回收器会自动释放分配给该对象的内存。 但无法预测进行垃圾回收的时间。 另外,垃圾回收器对窗口句柄或打开的文件和流等非托管资源一无所知。

将此接口的 Dispose 方法与垃圾回收器一起使用来显式释放非托管资源。 当不再需要对象时,对象的使用者可以调用此方法

因为 IDisposable.Dispose 实现由类型的使用者调用时,实例属于自己的资源不再需要,您应将包装在 SafeHandle (建议使用的替代方法) 的托管对象,则应该重写Object.Finalize 来释放非托管资源,忘记在使用者调用 Dispose条件下。

使用对象实现 IDisposable

才能直接,使用非托管资源需要实现 IDisposable 如果应用程序使用对象实现 IDisposable,不提供 IDisposable 实现。 而,那么,当您使用时完成,应调用对象的IDisposable.Dispose 实现。 根据编程语言中,可以为此使用以下两种方式之一:

  • 使用一种语言构造 (在 C# 和 Visual Basic 中的 using 语句。

  • 通过切换到实现 IDisposable.Dispose 的调用在 try/catch 块。


//使用一种语言构造 (在 C# 和 Visual Basic 中的 using 语句
using System;using System.IO;using System.Text.RegularExpressions;public class WordCount
{
   private String filename = String.Empty;
   private int nWords = 0;
   private String pattern = @"\b\w+\b"; 

   public WordCount(string filename)
   { 
        if (! File.Exists(filename))
                 throw new FileNotFoundException("The file does not exist.");
        this.filename = filename;
        string txt = String.Empty;
        using (StreamReader sr = new StreamReader(filename))
        {
             txt = sr.ReadToEnd();
             sr.Close();
         }
         nWords = Regex.Matches(txt, pattern).Count;
   } 
   public string FullName
   {
        get {
         return filename; 
         } 
    }
    public string Name
   {
         get { 
             return Path.GetFileName(filename); 
         } 
    }
    public int Count 
   { 
           get { 
               return nWords; 
           } 
   }
}
using System;
using System.IO;
using System.Text.RegularExpressions;
public class WordCount
{   
private String filename = String.Empty;   
private int nWords = 0;   
private String pattern = @"\b\w+\b"; 

   public WordCount(string filename)
   { 
        if (! File.Exists(filename))
                 throw new FileNotFoundException("The file does not exist.");      
       this.filename = filename;      
       string txt = String.Empty;
       StreamReader sr = null;
       try {
         sr = new StreamReader(filename);
         txt = sr.ReadToEnd();
         sr.Close();
      }catch {
      
      }
      finally {
               if (sr != null) sr.Dispose();     
      }
      nWords = Regex.Matches(txt, pattern).Count;
   } 
   public string FullName
   { 
       get {
        return filename; 
        } 
    }
    public string Name
   { 
       get { 
           return Path.GetFileName(filename); 
           } 
   }
   public int Count 
   { 
       get { 
           return nWords; 
           } 
    }
}