我正在将C++ API代码移植到.NET,并将函数调用WaitHandle.WaitAny作为WaitForMultipleObjects的替代函数,但是在使用.NET4进行调试时,我可以看到此函数已连接到
private static extern int WaitMultiple(
WaitHandle[] waitableSafeHandle,
int msTimeOut,
bool exitContext,
bool WaitAll);这让我觉得这个函数不适合这个端口。还有其他建议吗?
发布于 2011-09-15 21:08:41
确实,WaitHandle.WaitAny()不足以与WaitForMultipleObjects()的功能相匹敌。但是你也需要使用WaitHandle.WaitAll()。
WaitHandle.WaitAny()匹配将WaitAll参数设置为FALSE时调用的WaitForMultipleObjects(),.WaitHandle.WaitAll()将其与设置为TRUE.的WaitAll匹配
发布于 2011-09-15 21:08:18
几乎相同的签名和行为,所以它是一个很好的候选者。如果使用WaitAll=true调用WaitForMultipleObjects(),您也可以使用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(),但当您需要确保所有句柄都接收到一个信号时,它很有用。
发布于 2011-09-16 00:29:40
这很好,它在幕后使用了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)一样,知道远程处理请求何时可以为下一个请求挂起,以及知道线程何时处于安全状态以响应中止请求。
https://stackoverflow.com/questions/7431171
复制相似问题