C#中的Dispose模式
C#中的資源
在我們的程序中,使用資源后,需要釋放。那么在C#中的每一種資源,可以分為兩類:
- 托管資源:由CLR管理分配和釋放的資源,即由CLR里new出來的對象; - 非托管資源:不受CLR管理的對象,windows內核對象,如文件、數據庫連接、套接字、COM對象等;在我們的程序中,使用到了非托管資源,或者托管資源,最后都需要釋放。針對托管資源,DotNet的垃圾回收器會自動地回收托管資源,而非托管的資源,則需要自己進行處理。
那么,我們可以使用C#的Dispose模式來方便地釋放這些資源。
Disposal模式
要采用Dispose模式,需要讓類型繼承接口IDisposable,其標示了該類型是需要顯式釋放資源的,你需要調用我的Dispose方法。
先看一下IDisposable接口的定義:
namespace System {//// 摘要:// 定義一種釋放分配的資源的方法。[ComVisible(true)]public interface IDisposable{//// 摘要:// 執行與釋放或重置非托管資源相關的應用程序定義的任務。void Dispose();} }可見,IDisposable接口很簡單。
VS對IDisposable接口實現的支持
在VS.net中,對IDispose模式實現支持的非常好。可以自動生成代碼框架。
看看自動生成的代碼
#region IDisposable Support private bool disposedValue = false; // 要檢測冗余調用protected virtual void Dispose(bool disposing) {if (!disposedValue){if (disposing){// TODO: 釋放托管狀態(托管對象)。}// TODO: 釋放未托管的資源(未托管的對象)并在以下內容中替代終結器。// TODO: 將大型字段設置為 null。disposedValue = true;} }// TODO: 僅當以上 Dispose(bool disposing) 擁有用于釋放未托管資源的代碼時才替代終結器。 // ~ResourceMgr() { // // 請勿更改此代碼。將清理代碼放入以上 Dispose(bool disposing) 中。 // Dispose(false); // }// 添加此代碼以正確實現可處置模式。 public void Dispose() {// 請勿更改此代碼。將清理代碼放入以上 Dispose(bool disposing) 中。Dispose(true);// TODO: 如果在以上內容中替代了終結器,則取消注釋以下行。// GC.SuppressFinalize(this); } #endregion代碼中包含了 IDisposable的Dispose()方法,和其調用的protected virtual void Dispose(bool disposing)實現方法。
Dispose(bool)定義為protected virtual,可以在子類中進行override。
簡單解釋
實現方法借助了一個disposedValue標示變量,在接口的Dispose方法實現中,使用參數true來調用Dispose(bool)進行真正的釋放操作,在操作完成后,disposedValue置為true,標示完成了Dispose;如果再次調用,就直接跳過。
結合 Finalize Method
一般,我們在析構器中進行清理的工作,這就是C#的Finalize方法。
~Object ();我們可以在析構器Finalize方法中,進行必要的清理工作,以防止調用方沒有使用Dispose來正確地釋放資源。但要注意和Dispose的正確處理,防止多次釋放的錯誤。
最簡單地使用using語句
來自MS的示例:
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();}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(resource) { ... },系統會隱式地調用對應資源的Dispose()方法來釋放資源。
總結
以上是生活随笔為你收集整理的C#中的Dispose模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 删掉被2345篡改的IE起始页
- 下一篇: 小米8和小米8屏幕指纹版有什么区别(红米