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

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

>’EventWaitHandle’
>”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,并且根据我的愿景似乎更干净.

十分感谢!!!

您可以使用 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);
相关文章
相关标签/搜索