Reputation: 131
Why do we use Dispose(false)
?
Below code in Dispose pattern?
~MyClass ()
{
Dispose(false);
}
What happens if I use Dispose(true)
instead?
What happens If I skip this finalizer?
Upvotes: 1
Views: 98
Reputation: 81297
Ideally, any time code is finished with an object that implements IDisposable
, it would ensure that the object's Dispose
method gets called before it is abandoned. Sometimes, however, objects which implement IDisposable
get abandoned without being properly disposed.
Classes in .NET can ask the system to watch over instances and let them know if they seem to have been abandoned. This is done by overriding a method called Finalize
which is part of type Object
. If that method is overridden and has not been suppressed, and the system notices that an object would be eligible collection if not for the presence of an active finalizer, the system will move the system to a queue of objects whose Finalize
method should run as soon as practical and suppress further observations of the object (so the object will get one shot at running its Finalize
method, but after that will be eligible for collection).
For some reason I don't understand, the creators of C# decided to forbid programmers using that language from overriding the Finalize
method directly. Instead, it requires that they use a special syntax which in turn instructs the compiler to override Finalize
. A block of code marked with ~ClassName
will execute when the system notices an object has been abandoned and runs its Finalize
method.
Upvotes: 1
Reputation: 726
The idea of overriding the Finalize method using Destructurs (~) is to get the ability to dispose manage code or not. In your example you are passing false which is meant dispose managed resource. In the following example you can see it clearly. Note: See how I prevent call the Dispose method several times by using the private member "disposed".
public class Dog : IDisposable
{
// Prevent dispose from happening more than once
private bool disposed = false;
// IDisposable.Dispose
public void Dispose()
{
// Explicitly dispose of resources
DoDispose(true);
// Tell GC not to finalize us--we've already done it manually
GC.SuppressFinalize(this);
}
// Function called via Dispose method or via Finalizer
protected virtual void DoDispose(bool explicitDispose)
{
if (!disposed)
{
// Free some resources only when invoking via Dispose
if (explicitDispose)
FreeManagedResources(); // Define this method
// Free unmanaged resources here--whether via Dispose
// or via finalizer
FreeUnmanagedResources();
disposed = true;
}
}
// Finalizer
~Dog()
{
DoDispose(false);
}
}
Upvotes: 2