Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use DangerousAddRef when async native call
    primarykey
    data
    text
    <p>When calling a native function that takes IntPtr I understand how to do it with a Sync native function.</p> <pre><code> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void Operation(SafeHandle handle) { var mustReleaseSafeHandle = false; RuntimeHelpers.PrepareConstrainedRegions(); try { handle.DangerousAddRef(ref mustReleaseSafeHandle); if (mustReleaseSafeHandle) WinAPI.Operation(handle.DangerousGetHandle()); } finally { if (mustReleaseSafeHandle) handle.DangerousRelease(); } } </code></pre> <p>How do I ensure the DangerousRelease happens when the native function is async?</p> <p>Here is a pseudo example of my async attempt to add more context as Hans Passant suggests.</p> <pre><code> public static unsafe void Operation(SafeHandle fileHandle, SafeHandle nativeMemoryHandle, int offset) { var mustReleaseSafeHandle = false; var ioCompletionCallback = new IOCompletionCallback((code, bytes, overlap) =&gt; { if (mustReleaseSafeHandle) nativeMemoryHandle.DangerousRelease(); Overlapped.Free(overlap); }); var overlapped = new Overlapped(); var nativeOverlapped = overlapped.Pack(ioCompletionCallback, null); nativeMemoryHandle.DangerousAddRef(ref mustReleaseSafeHandle); if (mustReleaseSafeHandle) { var memoryStartLocation = IntPtr.Add(nativeMemoryHandle.DangerousGetHandle(), offset); if (!WinAPI.Operation(fileHandle, memoryStartLocation, offset, nativeOverlapped)) { nativeMemoryHandle.DangerousRelease(); Overlapped.Free(nativeOverlapped); } } else { Overlapped.Free(nativeOverlapped); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    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. This table or related slice is empty.
    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