异步方法和进度指示器

时间:2014-03-05 03:25:52

标签: c# .net multithreading asynchronous progress-bar

我有一个Silverlight应用程序正在进行多个异步调用:

我面临的问题是如何确定是否所有异步调用都已完成,以便我可以停止显示进度指示器。在下面的示例中,只要第一个异步方法返回,就会停止进度指示器。

有关如何解决此问题的任何提示?

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

}

public void finished1()
{
    stopprogressindicator();

}

public void finished2()
{
    stopprogressindicator();

}

2 个答案:

答案 0 :(得分:2)

您需要异步等待两种方法完成,目前只要方法完成,就会调用stopprogressindicator

重构您的代码以从Taskcallasync1返回callasync2然后您可以

var task1 = callasync1();
var task2 = callasync2();
Task.Factory.ContinueWhenAll(new []{task1, task2}, (antecedents) => stopprogressindicator());

答案 1 :(得分:1)

我喜欢使用Task API的想法,但在这种情况下,您可以只使用计数器:

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