繁体   English   中英

异步方法和进度指示器

[英]Async methods and progress indicator

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

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

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

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

}

public void finished1()
{
    stopprogressindicator();

}

public void finished2()
{
    stopprogressindicator();

}

您需要异步等待两种方法完成,目前您在任何方法完成后立即调用stopprogressindicator

重构您的代码以从callasync1callasync2返回Task然后您可以这样做

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

我喜欢使用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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM