« Back to blog

Calling Async Service Calls Iteratively in Silverlight

Well, i was posed with a rather strange situation today when i had to make Async Svc Calls from a Silverlight UI code. The issue was that i had to call a single service method in an iterative fashion, ideally in a loop. But the problem was that i was doing a lot of processing in the completed event handlers and the order of the processing was making a difference to my UI. Ideally, had it been sync calls, i would have finished it off in a for loop. And then i was introduced to the concept of Enumerators. Here is a pseudo code snippet for the same: private void _getData() { List<string>.Enumerator enumerator = ListSource.GetEnumerator(); //create the Enumerator If(enumerator.MoveNext()) { _getData(enumerator);//send the enumerator to the _getData function } }   private void _getData(List<string>.Enumerator enumerator) { ServiceClient client = ServiceHelper.GetServiceClient(); client.GetDataCompleted += new EventHandler(retrieveDataCallBack); client.GetDataAsync(arg1,enumerator); //send the enumerator in the userstate }   void retrieveDataCallBack(object sender, GetDataCompletedEventArgs e) { //perfrom operation on e.Result; Before that do a check on e.Error If((e.Userstate as List<string>.Enumerator).MoveNext()) { _getData(e.Userstate as List<string>.Enumerator); } }   It was good to learn something fresh after an eon. :)