Task Parallel is unstable, using 100% CPU at times

前端 未结 3 1747
甜味超标
甜味超标 2021-02-08 21:04

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

3条回答
  •  独厮守ぢ
    2021-02-08 21:37

    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)

提交回复
热议问题