2012-02-09 28 views
1

WaitHandle.WaitAll在Windows Phone(7.1)上執行時會引發NotSupportedException。這種方法有其他選擇嗎?Windows Phone上WaitHandle.WaitAll的替代軟件?

這是我的場景:我發射了一堆http web請求,並且我希望在我能繼續之前等待它們全部返回。我想確保如果用戶必須等待所有這些請求返回超過X秒(總計),則操作應該中止。

回答

1

您可以嘗試使用全局鎖定。

啓動一個新線程,並使用鎖來阻止調用者線程,並使用所需的超時值。

在新線程中,在句柄上循環並調用每個等待。循環結束後,發出鎖定信號。

是這樣的:

private WaitHandle[] handles; 

private void MainMethod() 
{ 
    // Start a bunch of requests and store the waithandles in the this.handles array 
    // ... 

    var mutex = new ManualResetEvent(false); 

    var waitingThread = new Thread(this.WaitLoop); 
    waitingThread.Start(mutex); 

    mutex.WaitOne(2000); // Wait with timeout 
} 

private void WaitLoop(object state) 
{ 
    var mutex = (ManualResetEvent)state; 

    for (int i = 0; i < handles.Length; i++) 
    { 
     handles[i].WaitOne(); 
    } 

    mutex.Set(); 
} 

另一個版本使用共享鎖的Thread.join代替:

private void MainMethod() 
{ 
    WaitHandle[] handles; 

    // Start a bunch of requests and store the waithandles in the handles array 
    // ... 

    var waitingThread = new Thread(this.WaitLoop); 
    waitingThread.Start(handles); 

    waitingThread.Join(2000); // Wait with timeout 
} 

private void WaitLoop(object state) 
{ 
    var handles = (WaitHandle[])state; 

    for (int i = 0; i < handles.Length; i++) 
    { 
     handles[i].WaitOne(); 
    } 
}