//非托管资源
class UnmanagedObject
{
//模拟非托管操作
public void DoUnmanagedWork()
{
Console.WriteLine("do unmanaged work now...");
}
//自定义非托管操作释放操作
public void DoCleanup()
{
Console.WriteLine("cleanup unmanaged resource now...");
}
}
//托管资源包装对象
class UnmanagedWrapper:IDisposable
{
protected ArrayList _notifies;
public delegate void DoCleanupDelegate();
public UnmanagedWrapper()
{
_notifies = new ArrayList();
}
//注册非托管资源
public void RegisterFinalizeNotify(DoCleanupDelegate method)
{
if(!_notifies.Contains(method))
_notifies.Add(method);
}
//注销非托管资源
public void UnregisterFinallizeNotify(DoCleanupDelegate method)
{
_notifies.Remove(method);
}
//分派提醒消息
protected void CallNotifies()
{
foreach(object o in _notifies)
{
((DoCleanupDelegate)o).DynamicInvoke(null);
}
}
//IDisposable 成员
public void Dispose()
{
CallNotifies();
}
}
class Application
{
[STAThread]
static void Main(string[] args)
{
UnmanagedWrapper w = new UnmanagedWrapper();
UnmanagedObject obj1 = new UnmanagedObject();
w.RegisterFinalizeNotify(new UnmanagedWrapper.DoCleanupDelegate(obj1.DoCleanup));
obj1.DoUnmanagedWork();
UnmanagedObject obj2 = new UnmanagedObject();
w.RegisterFinalizeNotify(new UnmanagedWrapper.DoCleanupDelegate(obj2.DoCleanup));
obj2.DoUnmanagedWork();
w.Dispose();
Console.Read();
}
}
//输出效果