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:
Related in same category :
-
-
-
-
-
|