Silverlight,处理异步调用

Bil*_*lly 6 .net c# silverlight

我有一些代码如下:

        foreach (var position in mAllPositions)
        {
                 DoAsyncCall(position);
        }
//I want to execute code here after each Async call has finished
Run Code Online (Sandbox Code Playgroud)

那我该怎么办呢?
我可以这样做:

        while (count < mAllPositions.Count)
        { 
            //Run my code here
        }
Run Code Online (Sandbox Code Playgroud)

并且在每次执行异步调用之后增加计数...但这似乎不是一种好方法

有什么建议?上述问题是否存在一些设计模式,因为我确定这是常见的情况?

Eri*_*ric 0

(注意,我给你两个单独的答案。这个答案尽可能接近你的问题。)

你的问题说

while{ count >= mAllPositions.Count )
{
    //Run my code here
}
Run Code Online (Sandbox Code Playgroud)

但我猜你真正的意思是:

while( count < mAllPositions.Count )
   ; // do nothing -- busy wait until the count has been incremented enough
// Now run my code here
Run Code Online (Sandbox Code Playgroud)

??

如果是这样,那么您可以使用信号量更有效地完成同样的事情:

Semaphore TheSemaphore = new Semaphore( 0, mAllPositions.Count );
Run Code Online (Sandbox Code Playgroud)

每个异步调用完成后,释放信号量。

TheSemaphore.Release();
Run Code Online (Sandbox Code Playgroud)

在执行最终代码之前,请确保信号量已被释放所需的次数:

 for( int i=0; i<mAllPositions.Count; i++ )
    TheSemaphore.WaitOne();
 // Now run follow-on code.
Run Code Online (Sandbox Code Playgroud)

您的代码将阻塞,直到异步操作全部完成。