WaitHandle.WaitAny来匹配WaitForMultipleObjects的功能

本文关键字:WaitForMultipleObjects 功能 WaitAny WaitHandle | 更新日期: 2023-09-27 18:08:35

我正在将C++ API代码移植到.NET,并查看函数调用WaitHandle.WaitAny作为WaitForMultipleObjects的替代品,但当使用.NET4调试时,我可以看到该函数被钩入

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

,这让我认为这个功能不适合端口。还有其他建议吗?

WaitHandle.WaitAny来匹配WaitForMultipleObjects的功能

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

  • WaitHandle.WaitAny()匹配WaitForMultipleObjects(), WaitAll参数设置为FALSE
  • WaitHandle.WaitAll()匹配WaitAll设置为TRUE

几乎相同的签名和行为,所以它是一个很好的候选者。如果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提供了另一个方法waithhandle . waitall(),但当您需要确保所有句柄都接收到信号时,它很有用。

很好,它在底层使用了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)一样,知道何时可以暂停远程请求以进行下一个请求,以及知道何时线程处于安全状态以执行中止请求。

相关文章:
  • 没有找到相关文章