Silverlight,处理异步调用 [英] Silverlight, dealing with Async calls
问题描述
我有一些代码如下:
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
}
并在每次 Async 调用后增加计数......但这似乎不是一个好方法
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?
推荐答案
鉴于您使用的是 Silverlight,并且您无权访问信号量,您可能正在寻找这样的东西(用记事本编写,所以没有承诺完美的语法):
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();
}
然而,Silverlight 强制您异步加载数据的好处之一是您必须努力工作以在进行服务调用时锁定 UI,而这正是您要做的处理这样的代码,除非你让它在后台线程上运行,我强烈建议你这样做.在后台进程完成之前,您始终可以显示请稍候"消息.
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.
这篇关于Silverlight,处理异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!