今天看代碼,看到IDispose然后牽涉到垃圾回收機制,最后又到Finalize折騰了一下午,現在終於了解.NET的一些運行機制了。
看到GC.SuppressFinalize方法(MSDN:http://msdn.microsoft.com/zh-cn/library/system.gc.suppressfinalize(v=VS.80).aspx中C#示例),代碼如下:
using System;
using System.ComponentModel;
// The following example demonstrates how to use the
// GC.SuppressFinalize method in a resource class to prevent
// the clean-up code for the object from being called twice.
public class DisposeExample
{
// A class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public class MyResource: IDisposable
{
// Pointer to an external unmanaged resource.
private IntPtr handle;
// Other managed resource this class uses.
private Component component = new Component();
// Track whether Dispose has been called.
private bool disposed = false;
// The class constructor.
public MyResource(IntPtr handle)
{
this.handle = handle;
}
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);//問題2:在“Dispose()”中“GC.SuppressFinalize(this);”是什么意思?
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();//問題1:也就是為什么GC垃圾回收機制在回收對象的時候只回收或者釋放非托管資源,而不回收托管資源?
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
CloseHandle(handle);
handle = IntPtr.Zero;
}
disposed = true;
}
// Use interop to call the method necessary
// to clean up the unmanaged resource.
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);//問題1:為什么在析構函數中調用的是“Dispose(false);”?
}
}
public static void Main()
{
// Insert code here to create
// and use a MyResource object.
}
}
產生了兩個問題(代碼中紅色標注區域):
問題1:為什么在析構函數中調用的是“Dispose(false);”,也就是為什么GC垃圾回收機制在回收對
象的時候只回收或者釋放非托管資源,而不回收托管資源?
問題2:在“Dispose()”中“GC.SuppressFinalize(this);”是什么意思?
上網搜了寫資料,終於了解了這種設計的用意和優點:
參考資料:
http://baike.baidu.com/view/4471636.htm
http://www.360doc.com/content/11/0503/18/6075898_114106056.shtml
解答問題1:
在.NET的對象中實際上有兩個用於釋放資源的函數:Dispose和Finalize。Finalize的目的是用於釋放非托管的資源,而Dispose是用於釋放所有資源,包括托管的和非托管的。
在這個模式中,通過一個變量“disposing”來區分是客戶調用(true)還是GC調用(false)。
這是因為,Dispose()函數是被其它代碼顯式調用並要求釋放資源的,而Finalize是被GC調用的。
在GC調用的時候MyResource所引用的其它托管對象(component)可能還不需要被銷毀,並且即使
要銷毀,也會由GC來調用。因此在Finalize中只需要釋放非托管資源即可。
解答問題2:
由於在Dispose()中已經釋放了托管和非托管的資源,因此在對象被GC回收時再次調用Finalize是
沒有必要的,所以在Dispose()中調用GC.SuppressFinalize(this)避免重復調用Finalize。
因此,上面的模式保證了:
1、 Finalize只釋放非托管資源;
2、 Dispose釋放托管和非托管資源;
3、 重復調用Finalize和Dispose是沒有問題的;
4、 Finalize和Dispose共享相同的資源釋放策略,因此他們之間也是沒有沖突的。
在C#中,這個模式需要顯式地實現,其中C#的~MyResource()函數代表了Finalize()。
優點:
1、如果客戶沒有調用Dispose(),未能及時釋放托管和非托管資源,那么在垃圾回收時,還有機會執
行Finalize(),釋放非托管資源,但是造成了非托管資源的未及時釋放的空閑浪費。
2、如果客戶調用了Dispose(),就能及時釋放了托管和非托管資源,那么該對象被垃圾回收時,不回
執行Finalize(),提高了非托管資源的使用效率並提升了系統性能。
此外還有Close()方法,此方法一般和Open()方法配合來使用,對於數據庫連接,一般可以逆向操作,比如打開->關閉,關閉->打開,而對於文件操作,一般是關閉文件,相當於Dispose(),而且有的用戶更願意使用Close()來釋放資源,所以出現了一下這種相當於適配器模式的代碼:
public void Close() { Dispose((); }
最后還要再說一點,據MSDN上說C#不允許類實現Finalize()方法,所以用析構函數來代替。
記於此,勿忘。
2012.03.07 17:01