深入了解C#系列:谈谈C#中垃圾回收与内存管理机制(2)
1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Data;
5using System.Data.Odbc;
6using System.Drawing;
7//Coded By Frank Xu Lei 18/2/2009
8//Study the .NET Memory Management
9//Garbage Collector 垃圾收集器。可以根据策略在需要的时候回收托管资源,
10//但是GC不知道如何管理非托管资源。如网络连接、数据库连接、画笔、组件等
11//两个机制来解决非托管资源的释放问题。析构函数、IDispose接口
12//COM引用计数
13//C++手动管理,New Delete
14//VB自动管理
15namespace MemoryManagement
16{
17 //继承接口IDisposable,实现Dispose方法,可以释放FrankClassDispose的实例资源
18 public class FrankClassWithDispose : IDisposable
19
{
20 private OdbcConnection _odbcConnection = null;
21
22 //构造函数
23 public FrankClassWithDispose()
24
{
25 if (_odbcConnection == null)
26 _odbcConnection = new OdbcConnection();
27 Console.WriteLine("FrankClassWithDispose has been created
");
28 }
29 //测试方法
30 public void DoSomething()
31
{
32
33 /**/////code here to do something
34 return ;
35 }
36 //实现Dispose,释放本类使用的资源
37 public void Dispose()
38
{
39 if (_odbcConnection != null)
40 _odbcConnection.Dispose();
41 Console.WriteLine("FrankClassWithDispose has been disposed
");
42 }
43 }
44 //没有实现Finalize,等着GC回收FrankClassFinalize的实例资源,GC运行时候直接回收
45 public class FrankClassNoFinalize
46
{
47 private OdbcConnection _odbcConnection = null;
48 //构造函数
49 public FrankClassNoFinalize()
50
{
51 if (_odbcConnection == null)
52 _odbcConnection = new OdbcConnection();
53 Console.WriteLine("FrankClassNoFinalize has been created
");
54 }
55 //测试方法
56 public void DoSomething()
57
{
58
59 //GC.Collect();
60 /**/////code here to do something
61 return ;
62 }
63 }
64 //实现析构函数,编译为Finalize方法,调用对象的析构函数
65 //GC运行时,两次调用,第一次没释放资源,第二次才释放
66 //FrankClassDestructor的实例资源
67 //CLR使用独立的线程来执行对象的Finalize方法,频繁调用会使性能下降
68 public class FrankClassWithDestructor
69
{
70 private OdbcConnection _odbcConnection = null;
71 //构造函数
72 public FrankClassWithDestructor()
73
{
74 if (_odbcConnection == null)
75 _odbcConnection = new OdbcConnection();
76 Console.WriteLine("FrankClassWithDestructor has been created
");
77 }
78 //测试方法
79 public void DoSomething()
80
{
81 /**/////code here to do something
82
83 return ;
84 }
85 //析构函数,释放未托管资源
86 ~FrankClassWithDestructor()
87
{
88 if (_odbcConnection != null)
89 _odbcConnection.Dispose();
90 Console.WriteLine("FrankClassWithDestructor has been disposed
");
91 }
92 }
93}
94
其中使用了非托管的对象OdbcConnection的实例。建立的客户端进行了简单的测试。客户端代码如下: