使用Register/Notify模式在C#中实现非托管资源的统一处置

//非托管资源
 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();
            }  
 }  

//输出效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值