Short question on how to use the Dispose Pattern
completely correctly.
I am disposing managed resources in my Dispose-method.
But, what about objects which are not disposable?
Like String
or System.Text.Decoder
or...
How do i handle these objects correctly. What happens if i don't set them to null
an if i don't let the GC finalize them GC.SupressFinalize(this);
?
Here is an example of how do I implemented the Pattern:
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