Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight, dealing with Async calls

I have some code as below:

        foreach (var position in mAllPositions)
        {
                 DoAsyncCall(position);
        }
//I want to execute code here after each Async call has finished

So how can I do the above?
I could do something like:

        while (count < mAllPositions.Count)
        { 
            //Run my code here
        }

and increment count after each Async call is made ... but this doesn't seem like a good way of doing it

Any advice? Is there some design pattern for the above problem as i'm sure it's a common scenario?

like image 351
Billy Avatar asked Feb 21 '10 23:02

Billy


1 Answers

Given that you're using Silverlight, and you don't have access to Semaphores, you might be looking for something like this (written in notepad, so no promises as to perfect syntax):

int completedCallCount = 0;
int targetCount = mAllPositions.Count;

using (ManualResetEvent manualResetEvent = new ManualResetEvent(false))
{
    proxy.DoAsyncCallCompleted += (s, e) =>
    {
        if (Interlocked.Increment(ref completedCallCount) == targetCount)
        {
            manualResetEvent.Set();
        }
    };

    foreach (var position in mAllPositions)
    {
        proxy.DoAsyncCall(position);
    }

    // This will wait until all the events have completed.
    manualResetEvent.WaitOne();
}

However, one of the benefits of Silverlight forcing you to asynchronously load data is that you have to work hard to lock the UI up when making a service calls, which is exactly what you're going to do with code like this, unless you have it running on a background thread, which I strongly recommend you do. You can always display a "please wait" message until the background process completes.

like image 184
Mike Goatly Avatar answered Oct 06 '22 00:10

Mike Goatly