如何等待2中的第一个:进程和EventWaitHandle

时间:2014-11-10 20:19:51

标签: c# process intptr waithandle

我想在两种不同的类型上使用WaitForMultipleObjects:

  • 'EventWaitHandle'
  • a'Process.Handle'==> IntPtr的

我不知道如何将(以适当的方式)“process.Handle”转换为WaitHandle以使以下代码有效:

   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);

我得到错误:

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

有人知道等待进程和EventWaitHandle的正确方法吗?

更新...我选择答案的原因。

首先感谢所有人:Jaroen,Slugart和Sriram。所有答案都非常好。

  • Jaroen解决方案因为我忽略的原因在我的机器上无效。我的'退出'事件从未发生过(也许只在Disposed?)。
  • Slugart解决方案运作良好,我在尝试之前尝试了它。
  • Sriram解决方案工作得很好,我选择了它,因为我没有创建一个错误的EventWaitHandle,根据我的愿景似乎更干净。

非常感谢!!!

3 个答案:

答案 0 :(得分:5)

您可以subclass the WaitHandle代表Process.Handle并使用该WaitHandle的实例等待。

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);

答案 1 :(得分:2)

进程句柄当然不是等待的,也不是和WaitHandle在同一个继承树中。您需要将它包装在一个事件中(它确实扩展了WaitHandle),例如:

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

所有WaitHandle实现都将使用SafeWaitHandle:"The SafeWaitHandle class is used by the System.Threading.WaitHandle class. It is a wrapper for Win32 mutexes and auto and manual reset events."

答案 2 :(得分:1)

您可以创建自己的EventWaitHandle并在Process.Exited事件中进行设置:

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