HandleRef 结构


将包含句柄的托管对象包装到通过平台调用传递到非托管代码的资源中。Wraps a managed object holding a handle to a resource that is passed to unmanaged code using platform invoke.

public value class HandleRef
public struct HandleRef
public struct HandleRef
type HandleRef = struct
Public Structure HandleRef



从 .NET Framework 2.0 开始,HandleRef 类的功能已被 SafeHandle 类及其派生类以及 CriticalHandle 类所取代。Starting with the .NET Framework 2.0, the functionality of the HandleRef class has been replaced by the SafeHandle class and its derived classes, as well as by the CriticalHandle class.

如果你使用平台调用来调用托管对象,并且在平台调用调用后不会在其他位置引用该对象,则垃圾回收器可能会完成托管对象。If you use platform invoke to call a managed object, and the object is not referenced elsewhere after the platform invoke call, it is possible for the garbage collector to finalize the managed object. 此操作将释放资源并使句柄无效,从而导致平台调用失败。This action releases the resource and invalidates the handle, causing the platform invoke call to fail. 使用 HandleRef 包装句柄可保证在平台调用完成之前不会对托管对象进行垃圾回收。Wrapping a handle with HandleRef guarantees that the managed object is not garbage collected until the platform invoke call completes. 有关平台调用服务的说明,请参阅使用非托管 DLL 函数For a description of platform invoke services, see Consuming Unmanaged DLL Functions.

HandleRef 值类型(如 GCHandle)是互操作封送拆收器识别的特殊类型。The HandleRef value type, like GCHandle, is a special type recognized by the interop marshaler. 正常的 nonpinned GCHandle 也会阻止不当垃圾回收,但 HandleRef 提供更好的性能。A normal, nonpinned GCHandle also prevents untimely garbage collection, yet HandleRef provides better performance. 尽管使用 HandleRef 在平台调用的持续时间内保持对象处于活动状态,但也可以将 GC.KeepAlive 方法用于相同的目的。Although using HandleRef to keep an object alive for the duration of a platform invoke call is preferred, you can also use the GC.KeepAlive method for the same purpose.

HandleRef 构造函数采用两个参数:表示包装的 Object,以及表示非托管句柄的 IntPtrThe HandleRef constructor takes two parameters: an Object representing the wrapper, and an IntPtr representing the unmanaged handle. 互操作封送拆收器仅将句柄传递给非托管代码,并保证包装(作为第一个参数传递给 HandleRef的构造函数)在调用期间保持活动状态。The interop marshaler passes only the handle to unmanaged code, and guarantees that the wrapper (passed as the first parameter to the constructor of the HandleRef) remains alive for the duration of the call.


HandleRef(Object, IntPtr)

用要包装的对象和由非托管代码使用的资源的句柄初始化 HandleRef 类的新实例。Initializes a new instance of the HandleRef class with the object to wrap and a handle to the resource used by unmanaged code.



获取资源的句柄。Gets the handle to a resource.


获取保存资源句柄的对象。Gets the object holding the handle to a resource.



返回 HandleRef 对象的内部整数表示形式。Returns the internal integer representation of a HandleRef object.


Explicit(HandleRef to IntPtr)

返回指定的 HandleRef 对象的资源的句柄。Returns the handle to a resource of the specified HandleRef object.