了解Finalize & Dispose & Close

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

 

posted @ 2013-05-23 10:50  zzq417  阅读(221)  评论(0编辑  收藏  举报