Protecting Against Double Disposal : IDisposable « Class Interface « C# / C Sharp






Protecting Against Double Disposal

 
using System;
public class MyClass : IDisposable
{
    private string name;
    public MyClass(string name) { this.name = name; }
    override public string ToString() { return name; }
   
    ~MyClass() 
    { 
        Dispose();
        Console.WriteLine("~MyClass()"); 
    }
   
    private bool AlreadyDisposed = false;
   
    public void Dispose()
    {
        if (!AlreadyDisposed)
        {
            AlreadyDisposed = true;
            Console.WriteLine("Dispose()");
            GC.SuppressFinalize(this);
        }
    }
}


public class MainClass
{
    public static void Main(string[] args)
    {
        MyClass t = new MyClass("Foo");
        Console.WriteLine(t);
   
        t.Dispose();
        t.Dispose();
   
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

 








Related examples in the same category

1.The IDisposable Interface
2.Derived Disposable Classes
3.The constructor initializes the internal object. The Dispose method closes the file resource. The destructor delegates to the Dispose method.
4.using statement with IDisposable interface
5.The Dispose Pattern