天天看点

.NET Garbage Collection 导致 unmanaged handle 提前释放 (SafeHandle)

这里是整理编辑一下我的原博文

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

继续阅读