1

I have a silverlight application which is making multiple async calls:

The problem I am facing is to how to determine if all the async calls are finished so that I can stop displaying the progress indicator. In the example below, progress indicator is stopped as soon as the first async method returns.

Any tips on how to resolve this ?

Constructor()
{
   startprogressindicator();
   callasync1(finished1);
   callasync2(finished2);
   //.... and so on

}

public void finished1()
{
    stopprogressindicator();

}

public void finished2()
{
    stopprogressindicator();

}

2 Answers 2

2

You need to asynchronously wait for both methods to finish, currently you call stopprogressindicator as soon as any of the method completes.

Refactor your code to return Task from callasync1 and callasync2 Then you can do

var task1 = callasync1();
var task2 = callasync2();
Task.Factory.ContinueWhenAll(new []{task1, task2}, (antecedents) => stopprogressindicator());
Sign up to request clarification or add additional context in comments.

Comments

1

I do like the idea of using Task API, but in this case you may simply use a counter:

int _asyncCalls = 0;

Constructor()
{
   startprogressindicator();

   Interlocked.Increment(ref _asyncCalls);
   try
   {
       // better yet, do Interlocked.Increment(ref _asyncCalls) inside
       // each callasyncN

       Interlocked.Increment(ref _asyncCalls);
       callasync1(finished1);

       Interlocked.Increment(ref _asyncCalls);
       callasync2(finished2);

       //.... and so on
   }
   finally
   {       
       checkStopProgreessIndicator();
   }
}

public checkStopProgreessIndicator()
{
   if (Interlocked.Decrement(ref _asyncCalls) == 0)
       stopprogressindicator();
}

public void finished1()
{
    checkStopProgreessIndicator()
}

public void finished2()
{
    checkStopProgreessIndicator()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.