Alternatives for WaitHandle.WaitAll on Windows Phone?

…衆ロ難τιáo~ 提交于 2019-12-11 09:36:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!