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

C# 如何等待2中的第一个:进程和EventWaitHandle,c#,process,intptr,waithandle,C#,Process,Intptr,Waithandle,我想等待两种不同类型的MultipleObjects: “EventWaitHandle” 一个'Process.Handle'==>intptr 我不知道如何(以适当的方式)将“process.Handle”转换为WaitHandle以使以下代码正常工作: var waitHandles = new WaitHandle[2]; waitHandles[0] = waitHandleExit; // Next line is the offending one: w

我想等待两种不同类型的MultipleObjects:

  • “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解决方案工作得非常完美,我选择它是因为我不会创建错误的EventWaitHandle,而且根据我的设想,它看起来更干净

非常感谢

您可以创建自己的EventWaitHandle并在事件上设置它:

您可以选择表示
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);

进程句柄不是自然可等待的,也不是与WaitHandle位于同一继承树中。您需要将其包装在事件中(扩展WaitHandle),例如:


所有WaitHandle实现都将使用SafeWaitHandle:

不会
resetEvent.SafeWaitHandle=
泄漏事件?为什么
新建SafeWaitHandle
?@N-ate上的
ownsHandle
参数将用于在处理时释放基础句柄(如果为true)。既然我们已经传递了false,它就不会处理进程句柄了。当然也有必要设置
EnableRaisingEvents
,但是这种方法在运行时是不必要的浪费。
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);
 ManualResetEvent resetEvent = new ManualResetEvent(true);
 resetEvent.SafeWaitHandle = new SafeWaitHandle(new IntPtr(process.Handle.ToPointer()), false);
 waitHandles[1] = = resetEvent;