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
[System.Runtime.InteropServices.ComVisible(true)]
public struct HandleRef
type HandleRef = struct
[<System.Runtime.InteropServices.ComVisible(true)>]
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 表示包装的,以及 IntPtr 表示非托管句柄的。The 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. |
属性
| Handle |
获取资源的句柄。Gets the handle to a resource. |
| Wrapper |
获取保存资源句柄的对象。Gets the object holding the handle to a resource. |
方法
| ToIntPtr(HandleRef) |
返回 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. |