Hi,
I was going through dispose pattern. I implemented IDisposable inteface with few codes and tried to dispose some object.
But not sure how the dispose method gets called.
Please find my code below:
public class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.TestMethod();
}
}
public class MyClass : IDisposable
{
StreamReader strReader;
private bool disposed = false;
public void TestMethod()
{
strReader = new StreamReader("TextFile1.txt");
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (strReader != null)
{
strReader.Dispose();
}
}
disposed = true;
}
}
#endregion
}
Now here, from where to call dispose method ?
Is that correct the way I am doing?
Is it that for each object that i create, I need to dispose it this way?
Thanks.
VulpesPosted Sep 4, 2012, 8:18 AM
The benefit of using a pattern here is that you can just implement it without having to think out all these aspects from scratch.
VulpesPosted Sep 4, 2012, 10:06 AM
In the .NET 4.0 version of the article which Sukesh found for version 2.0, it tells you that it is not necessary to create a finalizer (destructor in C#) for a class which contains a Stream as a field because it is not directly creating a file handle in the unmanaged heap:
http://msdn.microsoft.com/en-us/library/fs2xkftw(VS.100).aspx
In other words, the CLR will release the file handle anyway when MyClass (and the Stream before it) are GC'ed.
Sukesh MarlaPosted Sep 4, 2012, 8:49 AM
You are also required to do one more thing
Create Desctror as follow
~YouRClassName()
{
Dispose(false);
}
If You(user) forget to call dispose explictly Destrcuir will do the necessary task
Check this microst article
http://msdn.microsoft.com/en-us/library/fs2xkftw%28VS.80%29.aspx
one more thing you can like this'
Using(MyClass myClass = new MyClass())
{
myClass.TestMethod();
//myClass.Dispose(); Not required
}
Checj this is correct answer if it helped
Sumitra PaulPosted Sep 4, 2012, 7:19 AM
Here I don'nt understand one thing.
Just implementaing an interface i.e. IDisposable, why we call it as Pattern.
I mean is there anything else?
VulpesPosted Sep 4, 2012, 6:40 AM