0

I have the follow code for example

 static void Main(string[] args)
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            for (int i = 0; i < 100; i++)
            {
                new Task(()=> { DoCalc(); }).Start();
            }
            Console.ReadLine();
        }
        private static void DoCalc()
        {
            Console.WriteLine("I'm working");

        }

and I want to limit my cpu usage to 80%, how can I do it?

thanks a lot

  • 2
    Related https://superuser.com/questions/214566/are-there-solutions-that-can-limit-the-cpu-usage-of-a-process – Cleptus Aug 09 '18 at 07:07
  • So, you want your code to run slower than it could? Odd requirement. I could see e.g. *setting a lower priority* for the process/threads so that other processes aren't swamped out, but having the CPU *idle* when useful work could be done... – Damien_The_Unbeliever Aug 09 '18 at 07:09
  • tweaking a specific process or processes does not guarantee much because other processes could use CPU setting it greater to your limit, check the related question in superuser, I like the power management CPU limit option, no extra software required, – Cleptus Aug 09 '18 at 07:10
  • 1
    Possible duplicate of [How to limit CPU usage of a process](https://stackoverflow.com/questions/8776305/how-to-limit-cpu-usage-of-a-process) – DeveloperExceptionError Aug 09 '18 at 07:13
  • Do you want to reduce the *overall* cpu usage of the system, or just the cpu usage of your app? For the first, you should start on the OS level. For the latter, you can set the [Processor affinity](https://msdn.microsoft.com/en-us/library/system.diagnostics.process.processoraffinity.aspx) and don't use all available processors, or (as a poor man's approach) check how many processors there are and reduce the number of parallel tasks to be lower than the number of processors. – derpirscher Aug 09 '18 at 07:19
  • no, the client asked me that my process will never take more of 80% CPU, at my code lvel and not the OS – MrCamper Aug 09 '18 at 07:25
  • 1
    That is what he asked, but not what he meant. He wants you to avoid affecting the other programs that run on his machine. You do so by using the Thread.Priority property. If he's entirely too focused on the number, and not what it actually means, then you need to create less threads than Environment.ProcessorCount. – Hans Passant Aug 09 '18 at 07:52
  • It seems contradictory to set your process priority to high then try to constrain the total CPU usage. I have found on most systems that aren't otherwise overloaded that letting it use 100% but at idle priority gives both more clock cycles to your process and allows the system to be more responsive to other processes and user interactions. The CPU may say 100% but if your task manager was closed then you wouldn't notice. – Adam G Aug 09 '18 at 08:10

0 Answers0