簡體   English   中英

如何等待2中的第一個:進程和EventWaitHandle

[英]How to wait for the first of the 2: a process and an 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,並且根據我的願景似乎更干凈。

非常感謝!!!

您可以繼承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);

進程句柄當然不是等待的,也不像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.WaitHandle類使用。它是Win32互斥體以及自動和手動重置事件的包裝器。”

您可以創建自己的EventWaitHandle並在Process.Exited事件上設置它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM