Frank Dzaebel, erstellt am: 2.08.2006, zuletzt geändert:
8.03.2007
Kategorie: Implementation, .NET-Version: 2.0, [Download]
Selbst bei managed Klassen die managed Member enthalten, die IDisposable implementieren:
Der Garbage Collector führt die Freigabe des Objektes automatisch aus.
Durch Entwurfs-Pattern kann sichergestellt werden, dass dabei ein beliebiger Freigabe-Code aufgerufen wird.

Weiterführende Informationen, siehe:
- Garbage Collection,
-
Erkennen und Verhindern von Speicherverlusten in verwaltetem Code
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace GcDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.Text = MyClassInstances.ToString();
textBox2.Text = MyDispInstances.ToString();
}
MyClass myClass;
private void button1_Click(object sender,EventArgs e)
{
for (int i = 0; i < 1000; i++)
myClass = new MyClass();
textBox1.Text = MyClassInstances.ToString();
textBox2.Text = MyClassInstances.ToString();
}
public static int MyClassInstances = 0;
public static int MyDispInstances = 0;
}
class MyClass
{
public MyDisposable myclass = new MyDisposable();
public MyClass() { Form1.MyClassInstances++; }
~MyClass() { Form1.MyClassInstances--; }
}
public class MyDisposable : IDisposable
{
[DllImport("coredll.dll")]
static extern bool CloseHandle(IntPtr hObject);
private IntPtr handle;
private Component Components = null;
private bool disposed = false;
public MyDisposable()
{
Form1.MyDispInstances++;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
Components.Dispose();
}
if (handle != IntPtr.Zero) CloseHandle(handle);
handle = IntPtr.Zero;
}
disposed = true;
}
~MyDisposable()
{
Dispose(false);
Form1.MyDispInstances++;
}
public void DoSomething()
{
if (this.disposed)
{
throw new ObjectDisposedException("MeinObjekt");
}
}
}
}