A Dispose Pattern Example

If you want to control when an object’s unmanaged resources are released, you can follow the dispose pattern, implementing a Dispose method.
Here’s a complete example.  We create a method to release resources that is called either when a client invokesDispose directly or when the CLR is finalizing the object.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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);
    }
}