Search code examples
c#taskpinvoke

How do I await a HANDLE / SafeHandle?


I have a process HANDLE I got from a P/Invoke'd API. What is the moral equivalent of WaitForSingleObject or WaitOne that plays nicely with tasks?


Solution

  • I would wrap it up in a WaitHandle, like so:

        private class MyWaitHandle : System.Threading.WaitHandle {
            public MyWaitHandle(IntPtr handle) {
                this.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle(handle, true   /*change to false if you will manually close your handle*/);
            }
        }
    

    Then pass your p/invoked handle into the new MyWaitHandle and wait on it normally:

    using (var myWaitThing = new MyWaitHandle(hSomeUnmanagedHandle)) {
         myWaitThing.WaitOne();
    }
    

    Not sure what kind of niceties you are looking for when playing with tasks, but if you want a task that completes when your wait event is done, then fire off a Task that does nothing but wait for that WaitOne() to return, and then you can await that Task like any other.