Windows Phone 上 WaitHandle.WaitAll 的替代方案? [英] Alternatives for WaitHandle.WaitAll on Windows Phone?

查看:30
本文介绍了Windows Phone 上 WaitHandle.WaitAll 的替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

WaitHandle.WaitAll throws a NotSupportedException when executed on Windows Phone (7.1). Is there an alternative to this method?

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

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.

推荐答案

您可以尝试使用全局锁.

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.

类似于:

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 而不是共享锁的版本:

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

这篇关于Windows Phone 上 WaitHandle.WaitAll 的替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆