Материал из .Net Framework эксперт
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Complex IDisposable pattern
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;
class MyClass : IDisposable
{
private IntPtr myHandle = IntPtr.Zero;
~MyClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
IntPtr h = myHandle;
if (h != IntPtr.Zero)
{
h = IntPtr.Zero;
}
}
}
public class MainClass
{
public static void Main()
{
using (MyClass mc = new MyClass())
{
}
}
}
implementation of IDisposable
using System;
class MyClass: IDisposable
{
private bool Disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if(!this.Disposed)
{
if(disposing)
{
//free any managed resources
}
//free unmanaged resources
}
Disposed = true;
}
~MyClass()
{
Dispose(false);
}
}
Simple IDisposable pattern
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;
class MyClass : IDisposable
{
private Stream myStream = null;
public void Dispose()
{
Stream s = myStream;
if (s != null)
((IDisposable)s).Dispose();
}
}
public class MainClass
{
public static void Main()
{
using (MyClass mc = new MyClass())
{
}
}
}