saklo saklo - 1 year ago 94
C# Question

Parallel.Foreach for calling and consuming multiple function

I want to do a Parallel.ForEach(... ) for the below code snipet, however as there are two function calls - both should happend in the same block, as the second funtion is consuming the value returned by the first function. I don't know who to achive this. Basically I want to convert the below into a Parallel.ForEach(...). Thanks in advance.

List<Employee> employeeList = GetEmployees();

foreach (var emp in employeeList)
var empDetails = GetEmpDetails(emp.EmployeeId);


I already tried the below, it is not working:

Parallel.ForEach(employeeList, emp =>
var empDetails = GetEmpDetails(emp.EmployeeId);



Answer Source

It seems that you are using EF connection behind the scenes and that does not seem to be designed for this and executes multiple data retrieval is executed on the same command. You can read more about it here. It has the solution there as well: to enable MARS.

So as far as I can see there is no problem with the Parallel.ForEach, but the problem with some underlying stuff that is not possible to run in parallel out of the box.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download