Windows Phone上WaitHandle.WaitAll的替代方案?

时间:2012-02-09 06:43:24

标签: windows-phone-7 windows-phone-7.1 waithandle

WaitHandle.WaitAll在Windows Phone(7.1)上执行时抛出NotSupportedException。有这种方法的替代方案吗?

这是我的方案:我正在解雇一堆http网络请求,我想等待所有人返回才能继续。我想确保如果用户必须等待超过X秒(总计)以便返回所有这些请求,则应该中止操作。

1 个答案:

答案 0 :(得分:1)

您可以尝试全局锁定。

启动一个新线程,并使用一个锁来阻止调用者线程,并使用你想要的超时值。

在新线程中,循环句柄并在每个上调用wait。循环完成后,发出锁定信号。

类似的东西:

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();
    }
}