Protecting Against Double Disposal : IDisposable : Class Interface C# Source Code


Custom Search

C# Source Code » Class Interface » IDisposable »

 

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();
    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Class Interface
» IDisposable