關於如何完全正確使用Dispose Pattern
的簡短問題。 我在Dispose方法中處理託管資源。正確清潔非一次性物體
但物件哪一個是不是一次性? 與String
或System.Text.Decoder
或...
如何正確處理這些對象。如果我不將它們設置爲null
,如果我不讓GC完成它們,GC.SupressFinalize(this);
會發生什麼?
這裏是我怎麼實現的模式爲例:
private class RequestState : IDisposable {
const int BufferSize = 1024;
public StringBuilder RequestData;
public byte[] BufferRead;
public WebRequest Request;
public Stream ResponseStream;
// Create Decoder for appropriate enconding type.
public Decoder StreamDecode = Encoding.UTF8.GetDecoder();
public MyMamespace.Machine Machine;
public RequestState() {
BufferRead = new byte[BufferSize];
RequestData = new StringBuilder(String.Empty);
Request = null;
ResponseStream = null;
}
-------------------------------------------------------------------------------
#region IDisposable
private bool disposed = false;
public void Dispose() {
Dispose(true);
}
#region IDisposable
private bool disposed = false;
public void Dispose() {
Dispose(true);
// GC.SupressFinalize(this); // What happens if I tell the GC that this object is alredy finalized??
}
protected virtual void Dispose(bool disposing) {
if (!this.disposed) {
if (disposing) {
// Dispose managed resources.
ResponseStream.Dispose();
Machine = null; // Do I need this?
}
// release unmanaged ressources
disposed = true;
}
}
~RequestState() {
Dispose(false);
}
#endregion
}
#endregion
可能的重複:http://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface – Steve
@Steve,謝謝我正在尋找這樣的文章。這爲我在.NET中對清潔資源的混淆帶來了更多的光明 – Marschal