【发布时间】:2014-10-06 06:23:05
【问题描述】:
我有以下 PLINQ 查询:
// Let's get a few customers
List<Customer> customers = CustomerRepository.GetSomeCustomers();
// Let's get all of the items for all of these customers
List<CustomerItem> items = customers
.AsParallel()
.SelectMany(x => ItemRepository.GetItemsByCustomer(x))
.ToList();
我希望GetItemsByCustomer() 会为每个客户并行执行,但它会按顺序运行。
我试图强制并行但仍然没有运气:
List<CustomerItem> items = customers
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.SelectMany(x => ItemRepository.GetItemsByCustomer(x))
.ToList();
方法签名:
private IEnumerable<Item> GetItemsByCustomer(Customer customer)
{
// Get all items for a customer...
}
根据this article,如果 PLINQ 认为合适,当然可以采用顺序路由,但强制并行仍然应该覆盖它。
注意:以上示例仅用于说明 - 假设 customers 是一个小列表,GetItemsByCustomer 是一个昂贵的方法。
【问题讨论】:
-
你能举一个完整的、独立的例子吗?
-
你的真实代码是一样的还是你使用
SelectMany的重载,它以索引为参数? -
@SriramSakthivel:我的代码在结构上与上面的相同。
-
此外,您还应该指定如何衡量您的执行以得出结论它没有并行运行?
-
不要尝试使用并行来加速缓慢的数据访问代码!看起来您的代码尝试在通常使用 single 连接的 ORM 上下文上“并行”执行查询。这将强制所有查询按顺序执行。不要尝试执行多个查询,而是使用 ORM 的机制将所有请求批处理到单个请求,或者创建一个
GetItemsByCustomers方法,该方法接受您要使用的所有 ID 的列表并在 WHERE 子句中使用IN (...)参数
标签: c# .net linq task-parallel-library plinq