WaitHandle.WaitAny匹配WaitForMultipleObjects功能

时间:2011-09-15 12:53:06

标签: c# .net multithreading

我正在将C++ API代码移植到.NET并查看函数调用WaitHandle.WaitAny作为WaitForMultipleObjects的替代,但在使用.NET4进行调试时,我可以看到这个功能被挂钩了

private static extern int WaitMultiple(
                               WaitHandle[] waitableSafeHandle, 
                               int msTimeOut, 
                               bool exitContext, 
                               bool WaitAll);

这让我觉得这个函数不适用于端口。还有其他建议吗?

3 个答案:

答案 0 :(得分:8)

WaitHandle.WaitAny()确实不足以匹配WaitForMultipleObjects()的功能。但您只需要使用WaitHandle.WaitAll()

  • WaitHandle.WaitAny()匹配WaitForMultipleObjects()WaitAll参数设置为FALSE ,.
  • WaitHandle.WaitAll()与设置为WaitAll的{​​{1}}匹配。

答案 1 :(得分:3)

完全相同的签名和行为,所以它是一个很好的候选人。如果使用WaitForMultipleObjects()调用WaitAll=true,您也可以使用WaitHandle.WaitAll()

C++ WaitForMultipleObjects()

DWORD WINAPI WaitForMultipleObjects(
  __in  DWORD nCount,
  __in  const HANDLE *lpHandles,
  __in  BOOL bWaitAll,
  __in  DWORD dwMilliseconds
);
  

等待一个或所有指定的对象在信号中   状态或超时间隔过去


C# WaitHandle.WaitAny()

public static int WaitAny(
    WaitHandle[] waitHandles,
    TimeSpan timeout,
    bool exitContext
)
  

等待指定数组中的任何元素接收   信号,使用TimeSpan指定时间间隔并指定   是否在等待之前退出同步域。

.NET提供了另一种方法WaitHandle.WaitAll(),但在需要确保收到所有句柄信号时,它很有用。

答案 2 :(得分:2)

很好,它使用了引擎盖下的WaitForMultipleObjects()。您可以通过这个小测试程序找到它:

using System;
using System.Threading;

class Program {
    static void Main(string[] args) {
        var waits = new WaitHandle[65];
        for (int ix = 0; ix < waits.Length; ++ix) waits[ix] = new ManualResetEvent(false);
        WaitHandle.WaitAny(waits);
    }
}

WaitForMultipleObjects具有相同的限制。 WaitMultiple()方法标记为MethodImplOptions.InternalCall,因为它实际上位于CLR内部。哪个想了解阻塞等待以提供多个托管线程保证。就像在UI线程上抽取消息循环以保持COM满意(MsgWaitForMultipleObjects)一样,知道何时可以为下一个请求暂停远程处理请求并知道线程何时处于安全状态以遵守中止请求。