Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The point of both these structures is to prevent the garbage collector from releasing a resource and invalidating the handle before the P/Invoke call has finished. The documentation you linked indicates that these are special types recognized by the interop marshaller.</p> <p>What I gather from the documentation is that <code>HandleRef</code> is essentially a special case of the more general <code>GCHandle</code> structure.</p> <p>The <code>HandleRef</code> structure is specifically intended for wrapping handles to unmanaged resources that are used with P/Invoke code. For example, window handles (<code>HWND</code>) or device contexts (<code>HDC</code>). It has a <code>Handle</code> property that returns a value of type <code>IntPtr</code>, which is an integer value the size of a pointer on the underlying system's architecture. You can use this to quickly &amp; easily obtain the handle it wraps.</p> <p>Whereas the <code>GCHandle</code> structure allows one to specify the type of handle it wraps using one of the members of the <code>GCHandleType</code> enumeration, the <code>HandleRef</code> structure was specifically designed to wrap handles to unmanaged resources. You'd probably use the <code>GCHandle</code> structure when you're dealing directly with unmanaged memory, rather than the special handles that the Win32 API treats as black boxes.</p> <p>It is not necessary to use either. One can simply call <code>GC.KeepAlive</code> to keep the garbage collector from prematurely releasing the resource.</p> <p>And even that is probably not necessary. I've been writing P/Invoke code for years, and I've found that when it's correctly written, there's no need for either of these structures. If a class object gets garbage collected while the API call is in the middle of executing, then that's a bug in your application. I actually <em>want</em> to be notified of the failure via an exception, not hide it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload