I am porting C++ API
code to .NET
and looking into function call WaitHandle.WaitAny
as a replacement for WaitForMultipleObjects<
It is fine, it uses WaitForMultipleObjects() under the hood. Which you can find out with this little test program:
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);
}
}
Same restriction that WaitForMultipleObjects has. The WaitMultiple() method is marked MethodImplOptions.InternalCall because it actually lives inside the CLR. Which wants to know about blocking waits in order to provide several managed threading guarantees. Like pumping a message loop on a UI thread to keep COM happy (MsgWaitForMultipleObjects), knowing when a remoting request can be suspended for the next request and knowing when a thread is in a safe state to honor abort requests.
It is true that WaitHandle.WaitAny()
is not quite enough to match the functionality of WaitForMultipleObjects()
. But you just need to use WaitHandle.WaitAll()
as well.
WaitHandle.WaitAny()
matches WaitForMultipleObjects()
called with the WaitAll
parameter set to FALSE
,.WaitHandle.WaitAll()
matches it with WaitAll
set to TRUE
.Pretty the same signature and behaviour, so it is a good candidate. If WaitForMultipleObjects()
was called with WaitAll=true
you could use WaitHandle.WaitAll()
as well
C++ WaitForMultipleObjects()
DWORD WINAPI WaitForMultipleObjects(
__in DWORD nCount,
__in const HANDLE *lpHandles,
__in BOOL bWaitAll,
__in DWORD dwMilliseconds
);
Waits until one or all of the specified objects are in the signaled state or the time-out interval elapses
C# WaitHandle.WaitAny()
public static int WaitAny(
WaitHandle[] waitHandles,
TimeSpan timeout,
bool exitContext
)
Waits for any of the elements in the specified array to receive a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait.
.NET
provides an other method WaitHandle.WaitAll() but it usefull when you need to ensure that ALL handles are received a signal.