IDisposable資源釋放接口

微軟自帶的註釋摘要

// 摘要: 

    //     定義一種釋放分配的資源的方法。

    [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; 
           } 
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章