views:

550

answers:

1

In the code below, I have a List object. I want to iterate through each one and assign a value to one of the properties on each Item object. To get the value, I need to call an async method of a WCF service.

When the call to my WCF service completes, how do I take that data and assign it to the current instance (i) in itemsList? Is there a way to access i from my xxxCompleted event?

private void SomeMethod()
{
    List<Item> itemsList = GetItems();

    foreach(Item i in itemsList)
    {  
      MyClient client = new MyClient();
      client.GetSomeValueCompleted += client_GetSomeValueCompleted;
      client.GetSomeValueAsync(i.ID);
    } 
}   

private void client_GetSomeValueCompleted(object sender, GetSomeValueEventArgs e)
{
  int id = e.Result;
  //  how do I assign this ID to my itemsList object, i  ???
}
+2  A: 

You can pass the instance of MyClient class as the userstate on the async method call.

Take a look at this link


private void SomeMethod()
{    
   List itemsList = GetItems();    
   foreach(Item i in itemsList)    
   {        
      MyClient client = new MyClient();      
      client.GetSomeValueCompleted += client_GetSomeValueCompleted;      
      client.GetSomeValueAsync(i.ID, client);
   } 
}   

private void client_GetSomeValueCompleted(object sender, GetSomeValueEventArgs e)
{  
   int id = e.Result;  

   //  how do I assign this ID to my itemsList object, i  ???
   (e.UserState as MyClient).ID = id;
}


Klinger