Silverlight, dealing with Async calls

后端 未结 8 1295
走了就别回头了
走了就别回头了 2021-01-03 01:23

I have some code as below:

        foreach (var position in mAllPositions)
        {
                 DoAsyncCall(position);
        }
//I want to execute co         


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 01:47

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

    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.

提交回复
热议问题