I\'m currently testing out Parallel for C#. Generally it works fine, and using parallel is faster than the normal foreach loops. However, at times (like 1 out of 5 times), my
I had a similar problem. I am using octa-core I5 processor with 16GB RAM, Parallel.Foreach was hitting 100% CPU, after making a minor code change CPU utilization came down to under 20%. This is my sample code.
static void Main(string[] args)
{
List values = Enumerable.Range(1, 100000000).ToList();
long sum = 0;
Parallel.ForEach(values,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
x =>
AddValues(x, ref sum)
);
Console.WriteLine(sum);
}
private static long AddValues(int x, ref long sum)
{
PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
CheckCPUUsageAndSleepThread(cpuCounter);
int y = x * 5;
for (int i=0;i 80) //Check if CPU utilization crosses 80%
{
Thread.Sleep(1);
}
}
When CPU utilization crosses 80% I pause for 1 millisecond. This solved my problem. If you have a situation where you need to go with parallel.foreach loop, You could try calling this function, else you can try above solutions
CheckCPUUsageAndSleepThread()
I hope it helps.
PS: To simulate 100% CPU usage comment Thread.Sleep(1)