How to wait for the first of two: Process and EventWaitHandle

I want WaitForMultipleObjects on 2 different types:

  • a 'EventWaitHandle'
  • a 'Process.Handle' ==> intptr

I don't know how to convert (appropriately) "process.Handle" to WaitHandle to have the following code:

   var waitHandles = new WaitHandle[2];
   waitHandles[0] = waitHandleExit;
   // Next line is the offending one:
   waitHandles[1] = new SafeWaitHandle(process.Handle, false);
   int waitResult = WaitHandle.WaitAny(waitHandles, timeOut);

      

Im getting error:

Error   1   Cannot implicitly convert type 'Microsoft.Win32.SafeHandles.SafeWaitHandle' to 'System.Threading.WaitHandle' ...

      

Does anyone know the correct way to wait for the process and EventWaitHandle?

Update ... Reasons for choosing an answer.

First of all, thanks to everyone: Yaron, Slugart and Sriram. All answers were very pleasant.

  • Jaroen's solution for the reason I ignored didn't work on my machine. The "Exited" event never happened (perhaps only on Disposed?).
  • Slugart's solution worked great and I tried it before I canceled his answer.
  • Sriram's solution worked great and I decided to use it because I am not creating a false EventWaitHandle and it seems cleaner according to my vision.

Thanks a lot!

+3


source to share


3 answers


You can subclass the WaitHandle that represents Process.Handle

and use an instance of that WaitHandle

to wait.



public class ProcessWaitHandle : WaitHandle
{
    private readonly Process process;
    public ProcessWaitHandle(Process process)
    {
        this.process = process;
        this.SafeWaitHandle = new SafeWaitHandle(process.Handle, false);
    }
}

var waitHandles = new WaitHandle[2]
{
    waitHandleExit,
    new ProcessWaitHandle(process)
};
int waitResult = WaitHandle.WaitAny(waitHandles, timeOut);

      

+4


source


A process handler is not a natural expectation and does not sit in the same inheritance tree as WaitHandle. You need to wrap it in an event (which extends WaitHandle), for example:

 ManualResetEvent resetEvent = new ManualResetEvent(true);
 resetEvent.SafeWaitHandle = new SafeWaitHandle(new IntPtr(process.Handle.ToPointer()), false);
 waitHandles[1] = = resetEvent;

      



All WaitHandle implementations will use SafeWaitHandle: The SafeWaitHandle class is used by the System.Threading.WaitHandle class. It is a wrapper for Win32 and auto mutexes and manual reset events.

+2


source


You can create your own EventWaitHandle and set it to the Process.Exited event :

var waitHandle = new ManualResetEvent(false);
process.Exited += (sender, e) => waitHandle.Set()
waitHandles[1] = waitHandle;

      

+1


source







All Articles