在下面的代码中,我有一个List对象。我想迭代每一个并为每个Item对象的一个属性赋值。要获取该值,我需要调用WCF服务的异步方法。
当我对WCF服务的调用完成时,如何获取该数据并将其分配给itemsList中的当前实例(i)?有没有办法从我的xxxCompleted事件中访问i?
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 ???
}
答案 0 :(得分:3)
您可以在异步方法调用中将MyClient类的实例作为userstate传递。
看看这个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;
}