• 窗口close 后资源无法释放的问题


    最近碰到一个窗口close()后资源无法释放的问题,找了很久才发现原来时存在交叉引用,虽然close()但是该form的对象依然被其他对象所引用,所以垃圾收集器并不能回收该form所占的资源。

    public class DeviceManager : IDeviceMonitorStatusNotify
        {
          public IDeviceManagerNotify    deviceManagerNotify;
          public DeviceManager(IDeviceManagerNotify   notify)
            {
              deviceManagerNotify = notify;
            }
      
            public void ReleaseAll()
    10          {
    11             //do some release resource
    12          }
    13    }
    14   
    15  public MainForm()
    16     {
    17         deviceManager = new  DeviceManager(this);
    18         private void ExitMainForm_Click(object sender, EventArgs e)
    19            {                  
    20               deviceManager .ReleaseAll();
    21                this.Close();
    22            }
    23      }
    24   

    当MainForm 执行 this.Close()后 MainForm 和DeviceManager 所占的资源并不会被释放,因为MainForm 对象被DeviceManager 所引用、

    DeviceManager 对象被MainForm 所引用,形成了交叉引用 ,虽然执行Close方法但是并不能释放资源,垃圾收集器并不会执行资源收集。

    一个form关闭之前应该该对象是否被其他对象所引用,如果被引用则先将该对象的引用置为null,然后再close()才能释放该form所占的资源。

    public class DeviceManager : IDeviceMonitorStatusNotify
        {
          public IDeviceManagerNotify deviceManagerNotify;
          public DeviceManager(IDeviceManagerNotify notify)
            {
                  deviceManagerNotify = notify;
            }
      
            public void ReleaseAll()
    10          {
    11               //do some release resource
    12               //将对MainForm 的引用置为null
    13              deviceManagerNotify = null;
    14          }
    15    }
    16   
    17   
    18  public MainForm()
    19     {
    20         
    21         deviceManager = new DeviceManager(this);
    22         private void ExitMainForm_Click(object sender, EventArgs e)
    23              {  
    24                  deviceManager.ReleaseAll();
    25                   //将对DeviceManager 的引用置为null
    26                  LocalManagers._Instance.DeviceManager = null;
    27                   //没有交叉引用,close后资源可以被垃圾收集器回收
    28                   this.Close();
    29               }
    30      }
    31   
  • 相关阅读:
    Android——inflate 将一个xml中定义的布局找出来
    Android——显示单位px和dip以及sp的区别
    StrategyPattern (策略模式)
    Flyweight(享元模式)
    ComponentPattern (组合模式)
    Java子类属性继承父类属性
    BridgePattern(桥接模式)
    FacadePattern(门面模式)
    装饰者模式,适配器模式,代理模式区别
    DecoratorPattern(装饰器模式)
  • 原文地址:https://www.cnblogs.com/dyufei/p/2573931.html
Copyright © 2020-2023  润新知