C# IDisposable接口实现
时间:2011-01-17 来源:foyuliu
1: /// <summary>
2: /// Description of MyDisposable.
3: /// </summary>
4: public class MyDisposable : IDisposable
5: {
6: public MyDisposable(string name)
7: {
8: Name = name;
9: }
10:
11: public string Name{get;private set;}
12:
13: #region IDisposable Implementation
14: public void Dispose()
15: {
16: Dispose(true);
17: GC.SuppressFinalize(this);
18: }
19:
20: bool disposed = false;
21: protected void Dispose(bool disposing)
22: {
23: if (disposed)
24: return;
25: disposed = true;
26:
27: if (disposing)
28: Console.WriteLine("Disposing managed resource for " + Name);
29:
30: Console.WriteLine("Disposing unmanaged resource for " + Name);
31: }
32:
33: /// <summary>
34: /// Overrides finalizer
35: /// </summary>
36: ~MyDisposable()
37: {
38: Dispose(false);
39: }
40: #endregion
41: }
测试代码:
1: public static void Main(string[] args)
2: {
3: var activeDispose = new MyDisposable("I am Explicit Dispose");
4: var implicitDispose = new MyDisposable("I am implicit dispose");
5:
6: activeDispose.Dispose();
7: }
输出:
1. 参数化的Dispose(bool disposing)
a. 传入true表示释放托管资源和非托管资源,false表示仅释放非托管资源。
b. 此函数意在统一显式的Dispose和被动的 Finalizer 的实现。
2.
GC.SuppressFinalize(this)
通知垃圾回收器不要对该对象进行垃圾回收。因为已经显式请求释放过资源了,不再需要GC做处理,从GC队列中清除自己。
3. Finalizer
~MyDisposable()
GC对对象进行垃圾回收时调用,此时托管资源以被释放,只需对非托管资源进行清理即可,故在此处调用Dispose(false)。
相关阅读 更多 +