【问题标题】:Async methods and progress indicator异步方法和进度指示器
【发布时间】:2014-03-05 03:25:51
【问题描述】:
我有一个 silverlight 应用程序,它正在进行多个异步调用:
我面临的问题是如何确定是否所有异步调用都已完成,以便我可以停止显示进度指示器。在下面的示例中,进度指示器会在第一个异步方法返回时立即停止。
关于如何解决这个问题的任何提示?
Constructor()
{
startprogressindicator();
callasync1(finished1);
callasync2(finished2);
//.... and so on
}
public void finished1()
{
stopprogressindicator();
}
public void finished2()
{
stopprogressindicator();
}
【问题讨论】:
标签:
c#
.net
multithreading
asynchronous
progress-bar
【解决方案1】:
您需要异步等待这两种方法完成,目前您在任何方法完成后立即调用stopprogressindicator。
重构您的代码以从 callasync1 和 callasync2 返回 Task 然后你可以这样做
var task1 = callasync1();
var task2 = callasync2();
Task.Factory.ContinueWhenAll(new []{task1, task2}, (antecedents) => stopprogressindicator());
【解决方案2】:
我确实喜欢使用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()
}