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

本文关键字:第一个 进程 EventWaitHandle 何等待 等待 | 更新日期: 2023-09-27 18:29:59

我想在两种不同类型上等待多个对象:

  • "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,而且根据我的愿景,它似乎更干净

非常感谢!!!

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

您可以将代表Process.Handle的WaitHandle子类化,并使用该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);

您可以创建自己的EventWaitHandle并在进程上设置它。退出的事件:

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

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

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

所有的WaitHandle实现都将使用一个SafeWaitHandle:"SafeWaitHandle类由System.Threading.WaitHandler类使用。它是Win32互斥以及自动和手动重置事件的包装器。"