WaitHandle.WaitAny匹配WaitForMultipleObjects功能

use*_*567 5 .net c# multithreading

我正在移植C++ API代码.NET并查看函数调用WaitHandle.WaitAny作为替换,WaitForMultipleObjects但是当.NET4我使用i进行调试时可以看到此函数被挂钩

private static extern int WaitMultiple(
                               WaitHandle[] waitableSafeHandle, 
                               int msTimeOut, 
                               bool exitContext, 
                               bool WaitAll);
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*nan 8

确实,这WaitHandle.WaitAny()还不足以匹配其功能 WaitForMultipleObjects().但你也需要使用WaitHandle.WaitAll()它.

  • WaitHandle.WaitAny()比赛WaitForMultipleObjects()被称为与WaitAll设定参数FALSE.
  • WaitHandle.WaitAll()将它与WaitAll设置匹配TRUE.


sll*_*sll 3

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

C++ WaitForMultipleObjects()

DWORD WINAPI WaitForMultipleObjects(
  __in  DWORD nCount,
  __in  const HANDLE *lpHandles,
  __in  BOOL bWaitAll,
  __in  DWORD dwMilliseconds
);
Run Code Online (Sandbox Code Playgroud)

等待直到一个或所有指定对象处于有信号状态或超时间隔已过


C# WaitHandle.WaitAny()

public static int WaitAny(
    WaitHandle[] waitHandles,
    TimeSpan timeout,
    bool exitContext
)
Run Code Online (Sandbox Code Playgroud)

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

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