這裡是整理編輯一下我的原博文
http://sheenspace.wordpress.com/2010/09/19/question-about-net-gc/
從.NET 2.0開始,加入了SafeHandle類用來避免unmaged資源被提前非預期的釋放。關于SafeHandle,參看MSDN:
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.aspx
這裡用一個例子重制IntPtr被提前釋放的情況:
class C1
{
// Some unmanaged resource handle
IntPtr _handle = IntPtr.Zero;
static void OperateOnHandle(IntPtr h)
{
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("After GC.Collect() call");
// Use the IntPtr here. Oops, invalid operation
}
public void m()
{
OperateOnHandle(_handle);
}
~C1()
{
// Release and destroy IntPtr here
Console.WriteLine("In destructor");
}
}
class Program
{
static void Main(string[] args)
{
C1 aC = new C1();
aC.m();
}
}
該例子由MSDN專家cbrumme文章中代碼改造而來
http://blogs.msdn.com/b/cbrumme/archive/2003/04/19/51365.aspx?wa=wsignin1.0