I have the below code with a parallel loop and the parallel loop calls another method Process() and waits on it.
var index = 0;
var options = new ParallelOptions { MaxDegreeOfParallelism = maxParallelCount };
ParallelLoopResult result = Parallel.ForEach(customers, options, async cust =>
{
var currentCount = Interlocked.Increment(ref index);
Console.WriteLine("Processing {0}/{1}", currentCount, totalCount);
var success = await Process(cust);
if (success)
Console.WriteLine("({0}/{1}) SUCCESS", cust.Name, cust.Number);
else
Console.WriteLine("({0}/{1}) FAILED", cust.Name, cust.Number);
});
if (result.IsCompleted)
Console.WriteLine("process completed | {0} customers processed.", totalCount);
When I run this code, I see the console logs in the following order. Why is the ParallelLoopResult not waiting for the method Process() to finish ? How can I improve this code to wait for the Process() to finish ?
process completed | 10 customers processed.
Customer Name1/Number1 SUCCESS
Customer Name1/Number4 SUCCESS
Customer Name1/Number3 SUCCESS
Customer Name1/Number2 SUCCESS
etc..
Expected order
Customer Name1/Number1 SUCCESS
Customer Name1/Number4 SUCCESS
Customer Name1/Number3 SUCCESS
Customer Name1/Number2 SUCCESS
etc..
process completed | 10 customers processed.