zoukankan      html  css  js  c++  java
  • Dispose Pattern总结

    1, CLR's Garbage Collector free you of managing the memory that are allocated in managed heap. But you need to clean up other native resource by yourself.

    You can use the object's finalizer to ensure that the native resources hold by this object are released when they are not needed.

    2, But GC does not run the finalizer deterministically, not deterministic time, not deterministic order. So you need disposable object that implement IDisposable interface. GC does not know this interface.

    3, Your host class that hold resources implement IDisposable interface. The consumer call dispose to free the expensive resource as soon as they are not needed.

    4, But if you host class hold native and managed resource( finalizable objects), you should not free managed resource in your finalizer because the order of running finializer is not deterministically. So you might free your resource which might be finalized prior to the host object that has been finalized. But in Dispose method, it is safe to free managed and native resource.

    5, The code in finializer and Dispose method might be duplicated. But just a little different. So you should use Dispose pattern. The code like this:

     

    public class DisposableClass : IDisposable

    {

        ‾DisposableClass()

        {

            Dispose(false);

        }

     

        public void Dispose()

        {

            Dispose(true);

            GC.SuppressFinalize(this);

        }

     

        protected virtual void Dispose(bool disposing)

        {

            if (disposing)

            {

                // Clean up all managed resources( finializable objects )

            }

               

            // Clean up all native resources

        }

    }

  • 相关阅读:
    Network Simulator for P4(NSP4) src内容介绍
    解决 E: Unable to correct problems, you have held broken packages. 问题
    【旧版本】Ubuntu 14.04 下 P416编译器 p4c的安装
    Ubuntu 14.04 更新gcc版本至4.9.2
    Ubuntu 14.04 下 安装Protocol Buffers
    Ubuntu 14.04 删除软件附加依赖
    解决Floodlight界面无法显示问题
    OpenVirteX 创建简易虚拟网络
    2017年P4中国峰会北京站 会议小结
    406. Queue Reconstruction by Height
  • 原文地址:https://www.cnblogs.com/caoshenghe/p/1574049.html
Copyright © 2011-2022 走看看