最近碰到一个窗口close()后资源无法释放的问题,找了很久才发现原来时存在交叉引用,虽然close()但是该form的对象依然被其他对象所引用,所以垃圾收集器并不能回收该form所占的资源。
1 | public class DeviceManager : IDeviceMonitorStatusNotify |
2 | { |
3 | public IDeviceManagerNotify deviceManagerNotify; |
4 | public DeviceManager(IDeviceManagerNotify notify) |
5 | { |
6 | deviceManagerNotify = notify; |
7 | } |
8 | |
9 | 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所占的资源。
1 | public class DeviceManager : IDeviceMonitorStatusNotify |
2 | { |
3 | public IDeviceManagerNotify deviceManagerNotify; |
4 | public DeviceManager(IDeviceManagerNotify notify) |
5 | { |
6 | deviceManagerNotify = notify; |
7 | } |
8 | |
9 | 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 |