关于如何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