相关疑难解决方法(0)

在Parallel.ForEach中嵌套等待

在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();
Run Code Online (Sandbox Code Playgroud)

c# wcf task-parallel-library async-await parallel.foreach

159
推荐指数
9
解决办法
10万
查看次数

Parallel.ForEach vs Task.Run和Task.WhenAll

使用Parallel.ForEach或Task.Run()以异步方式启动一组任务有什么区别?

版本1:

List<string> strings = new List<string> { "s1", "s2", "s3" };
Parallel.ForEach(strings, s =>
{
    DoSomething(s);
});
Run Code Online (Sandbox Code Playgroud)

版本2:

List<string> strings = new List<string> { "s1", "s2", "s3" };
List<Task> Tasks = new List<Task>();
foreach (var s in strings)
{
    Tasks.Add(Task.Run(() => DoSomething(s)));
}
await Task.WhenAll(Tasks);
Run Code Online (Sandbox Code Playgroud)

c# async-await parallel.foreach

144
推荐指数
2
解决办法
7万
查看次数