Implementing Finalize and Dispose to Clean Up Unmanaged Resources

2019/7/22 10:45:31 人评论 次浏览 分类:学习教程

原文链接:http://www.cnblogs.com/hongyu/archive/2011/04/28/2031938.html
1 // Design pattern for a base class.
2 public class Base: IDisposable
3 {
4 private bool disposed = false;
5
6 //Implement IDisposable.
7 public void Dispose()
8 {
9 Dispose(true);
10 GC.SuppressFinalize(this);
11 }
12
13 protected virtual void Dispose(bool disposing)
14 {
15 if (!disposed)
16 {
17 if (disposing)
18 {
19 // Free other state (managed objects).
20 }
21 // Free your own state (unmanaged objects).
22 // Set large fields to null.
23 disposed = true;
24 }
25 }
26
27 // Use C# destructor syntax for finalization code.
28 ~Base()
29 {
30 // Simply call Dispose(false).
31 Dispose (false);
32 }
33 }
34
35 // Design pattern for a derived class.
36 public class Derived: Base
37 {
38 private bool disposed = false;
39
40 protected override void Dispose(bool disposing)
41 {
42 if (!disposed)
43 {
44 if (disposing)
45 {
46 // Release managed resources.
47 }
48 // Release unmanaged resources.
49 // Set large fields to null.
50 // Call Dispose on your base class.
51 disposed = true;
52 }
53 base.Dispose(disposing);
54 }
55 // The derived class does not have a Finalize method
56 // or a Dispose method without parameters because it inherits
57 // them from the base class.
58 }

转载于:https://www.cnblogs.com/hongyu/archive/2011/04/28/2031938.html

相关资讯

    暂无相关的资讯...

共有访客发表了评论 网友评论

验证码: 看不清楚?
    -->