I have the following PLINQ query:
// 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();
I would expect GetItemsByCustomer()
to be executed in parallel for each customer, but it runs sequentially.
I have tried to force parallelism but still without luck:
List<CustomerItem> items = customers
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.SelectMany(x => ItemRepository.GetItemsByCustomer(x))
.ToList();
The method signature:
private IEnumerable<Item> GetItemsByCustomer(Customer customer)
{
// Get all items for a customer...
}
According to this article, PLINQ can certainly take the sequential route if it deems fit, but forcing parallelism should still override this.
Note: This above example is purely illustrative - assume customers
to be a small list and GetItemsByCustomer
to be an expensive method.
SelectMany
's overload which takes an index as parameter? – BurningScheduling.DefaultDegreeOfParallelism
defaults toMath.Min(Environment.ProcessorCount, 512)
. – SophisticatedGetItemsByCustomers
method that accepts a list of all IDs you want to use and uses anIN (...)
argument in the WHERE clause – FiddlestickItemRepository
thread-safe? – Finnegan