2011-09-15 57 views
5

我移植C++ API代碼.NET和尋找到的函數調用WaitHandle.WaitAnyWaitForMultipleObjects的替代品,但與.NET4調試時,我可以看到這個功能掛鉤到WaitHandle.WaitAny匹配WaitForMultipleObjects的功能

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

和這讓我覺得這個功能對於這個端口是不可修改的。還有其他建議嗎?

+2

爲什麼不呢?它允許指定多個等待句柄 – sll

+3

爲什麼你認爲WaitAny不適合? – dtb

回答

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 
) 

等待任何指定的數組中的元素的接收 信號,利用時間跨度,以指定的時間間隔,並指定 是否退出的等待前同步域。

.NET提供了另一種方法WaitHandle.WaitAll()但是當你需要確保所有句柄接收的信號是有用的。

8

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

  • WaitHandle.WaitAny()匹配WaitForMultipleObjects()稱爲與WaitAll參數設置爲FALSE
  • WaitHandle.WaitAll()匹配WaitAll設置爲TRUE
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)一樣,知道何時可以暫停下一個請求的遠程請求,以及知道何時線程處於安全狀態以遵從中止請求。