在一个 Metro 应用中,我需要执行多个 WCF 调用。由于需要进行大量的调用,因此我需要在并行循环中执行它们。但是问题在于,在 WCF 调用完成之前并行循环就已经退出了。
你会如何重构代码以满足预期功能?
var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var customers = new System.Collections.Concurrent.BlockingCollection<Customer>();
Parallel.ForEach(ids, async i =>
{
ICustomerRepo repo = new CustomerRepo();
var cust = await repo.GetCustomer(i);
customers.Add(cust);
});
foreach ( var customer in customers )
{
Console.WriteLine(customer.ID);
}
Console.ReadKey();
Parallel.ForEachAsync
API。 - Theodor Zoulias