我想在两种不同的类型上使用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。所有答案都非常好。
非常感谢!!!
答案 0 :(得分:5)
您可以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);
答案 1 :(得分:2)
进程句柄当然不是等待的,也不是和WaitHandle在同一个继承树中。您需要将它包装在一个事件中(它确实扩展了WaitHandle),例如:
ManualResetEvent resetEvent = new ManualResetEvent(true);
resetEvent.SafeWaitHandle = new SafeWaitHandle(new IntPtr(process.Handle.ToPointer()), false);
waitHandles[1] = = resetEvent;
所有WaitHandle实现都将使用SafeWaitHandle:"The SafeWaitHandle class is used by the System.Threading.WaitHandle class. It is a wrapper for Win32 mutexes and auto and manual reset events."
答案 2 :(得分:1)
您可以创建自己的EventWaitHandle并在Process.Exited事件中进行设置:
var waitHandle = new ManualResetEvent(false);
process.Exited += (sender, e) => waitHandle.Set()
waitHandles[1] = waitHandle;