Threading multiple async calls

后端 未结 2 1830
余生分开走
余生分开走 2021-01-01 00:41

Part of my Silverlight application requires data from three service requests. Up until now I\'ve been chaining the requests so as one completes the other starts... until the

2条回答
  •  轮回少年
    2021-01-01 01:10

    It could be done using the WaitHandle in the IAsyncResult returned by each async method.

    The code is simple. In Silverlight I just do 10 service calls that will add an item to a ListBox. I'll wait until all the service calls end to add another message to the list (this has to run in a different thread to avoid blocking the UI). Also note that adding items to the list have to be done through the Dispatcher since they will modify the UI. There're a bunch of lamdas, but it's easy to follow.

     public MainPage()
            {
                InitializeComponent();
                var results = new ObservableCollection();
                var asyncResults = new List();
                resultsList.ItemsSource = results;
                var service = new Service1Client() as Service1;
    
                1.To(10).Do(i=>
                    asyncResults.Add(service.BeginDoWork(ar =>
                        Dispatcher.BeginInvoke(() => results.Add(String.Format("Call {0} finished: {1}", i, service.EndDoWork(ar)))),
                        null))
                );
    
                new Thread(()=>
                {
                    asyncResults.ForEach(a => a.AsyncWaitHandle.WaitOne());
                    Dispatcher.BeginInvoke(() => results.Add("Everything finished"));
                }).Start();
            }
    

    Just to help with the testing, this is the service

    public class Service1
        {
            private const int maxMilliSecs = 500;
            private const int minMillisSecs = 100;
            [OperationContract]
            public int DoWork()
            {
                int millisSecsToWait = new Random().Next(maxMilliSecs - minMillisSecs) + minMillisSecs;
                Thread.Sleep(millisSecsToWait);
                return millisSecsToWait;
            }
        }
    

提交回复
热议问题