1

WaitHandle.WaitAll 在 Windows Phone (7.1) 上执行时会引发 NotSupportedException。这种方法有替代方法吗?

这是我的场景:我正在触发一堆 http web 请求,我想等待所有请求都返回,然后才能继续。我想确保如果用户必须等待超过 X 秒(总共)才能返回所有这些请求,则应该中止操作。

4

1 回答 1

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();
    }
}
于 2012-02-09T09:13:58.790 回答