Code Heaven For C# Developer

Wednesday, December 14, 2011

Dispose vs Finalize in C#

Dispose/Finalized Pattern

.Microsoft recommends that you implement both Dispose and Finalize when working with unmanaged resources. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly.
.Cleanup the unmanaged resources in the Finalize method and the managed ones in the Dispose method, when the Dispose/Finalize pattern has been used in your code.
.Structures and class can both implement IDisposable (unlike overriding Finalize(), which is for class types only)
.Dispose is never called by GS
.Disposed is executed as soon as you call it, and Finalized only when GC in a right mood for that.

class MyResourceWrapper:IDisposable
{
~MyResourceWrapper()
{
//Clean up unmanaged resources here
Console.WriteLine("MyResourceWrapper is finalized");
}
public void Dispose()
{
//Clean up unmanaged resources here
Console.WriteLine("MyResourceWrapper is disposed");
}
}
class ClassWithoutAnyting
{
}

static void Main(string[] args)
{
MyResourceWrapper ForFinalizeOnly = new MyResourceWrapper();
ForFinalizeOnly = null;
MyResourceWrapper ForFinalizeAndDispose = new MyResourceWrapper();
ForFinalizeAndDispose.Dispose();
ForFinalizeAndDispose = null;
//If you are bored to type Disposed, you can type "using" instead
using (MyResourceWrapper ForFinalizeAndDispose1 = new MyResourceWrapper()){}
//There is a compile error if you utilizing "using" with object
//without Dispose method implemented
//*** Compile ERROR!
using (ClassWithoutAnyting newclass = new ClassWithoutAnyting()){}

GC.Collect();
GC.WaitForPendingFinalizers();
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home