[英]How to wait for the first of the 2: a process and an EventWaitHandle
我想在2種不同的類型上使用WaitForMultipleObjects:
我不知道如何將(以適當的方式)“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。 所有答案都非常好。
非常感謝!!!
您可以繼承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.