了解Finalize & Dispose & Close

本文详细解释了Finalize与Dispose方法在资源释放方面的区别及使用场景。Dispose采用显式方式,通常由程序员直接调用,并负责托管和非托管资源的释放;而Finalize则为隐式,由垃圾回收器调用,主要负责非托管资源的释放。文章还通过示例代码展示了如何正确实现这两个方法。

Finalize& Dispose are all release resources, and their function should be the same.The difference between them is, Finalize is in implicit way, and dispose is inexplicit. Another difference is finalize will be called by GC, but dispose is being called by coder.So dispose should run GC.SuppressFinalize(), and don't forget to override finalize

Close:Official has no limit that 'close' just mean release resource. Usually, there are only one method, close or dispose which do release resource and in public.

Let's look a sample

 1 public class AuthorizeBackup : IDisposable
 2     {
 3         private bool _disposed = false;
 4         private System.IO.FileStream fs = new System.IO.FileStream("", System.IO.FileMode.Create);
 5         private Dictionary<string, string> dic = new Dictionary<string, string>();
 6 
 7         public void Dispose()
 8         {
 9             Dispose(true);
10             GC.SuppressFinalize(this);
11         }
12 
13         protected virtual void Dispose(bool disposing)
14         {
15             //允许多次调用
16             if (!_disposed)
17             {
18                 //主动调用时,也释放managed resource
19                 if (disposing)
20                 {
21                     
22                 }
23                 //释放unmanaged resource
24                 fs.Close();
25 
26                 _disposed = true;
27             }
28         }
29 
30         ~AuthorizeBackup()
31         {
32             Dispose(false);
33         }
34     }
View Code

Add a derive class

 1 public class RoleAuthorizeBuckup : AuthorizeBackup
 2     {
 3         private System.IO.BinaryWriter _write;
 4         private bool _disposed = false;
 5 
 6         protected override void Dispose(bool disposing)
 7         {
 8             if (!_disposed)
 9             {
10                 if (disposing)
11                 {
12                     
13                 }
14                 _write.Close();
15                 _disposed = true;
16                 base.Dispose(disposing);
17             }
18         }
19     }
View Code

 

转载于:https://www.cnblogs.com/zzq417/archive/2013/05/23/Finalize_Dispose.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值