问题
WaitHandle.WaitAll throws a NotSupportedException when executed on Windows Phone (7.1). Is there an alternative to this method?
Here's my scenario: I am firing off a bunch of http web requests and I want to wait for all of them to return before I can continue. I want to make sure that if the user has to wait for more than X seconds (in total) for all of these requests to return, the operation should be aborted.
回答1:
You can try with a global lock.
Start a new thread, and use a lock to block the caller thread, with the timeout value you want.
In the new thread, loop on the handles and call wait on each. When the loop is done, signal the lock.
Something like:
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();
}
Another version using Thread.Join instead of a shared lock:
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();
}
}
来源:https://stackoverflow.com/questions/9206520/alternatives-for-waithandle-waitall-on-windows-phone