Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict the CPU usage a C# program takes?

Tags:

c#

cpu

I am developing a C# program, and i have one function that consumes too much CPU. I would like to know a way to control this by code (not with any external application) and restrict the percentage of CPU usage. For example, if it uses 90% of the CPU usage, to make my app consume only a 20%, even if it becomes slower. It must be done automatically and from within the app. If you provide a class, it would be fantastic.

like image 895
netadictos Avatar asked Oct 30 '08 18:10

netadictos


People also ask

Why is my CPU usage at 70%?

It is normal for it to be high because the processor is not doing much at the moment. So, if your System Idle process is using 60% - 70% of your CPU, it means you're actually using 40% - 30% of it. Was this reply helpful? No the System Idle Process is only using 20-30% when running no or very few programs.


1 Answers

I don't know if you can do that, but you can change the thread priority of the executing thread via the Priority property. You would set that by:

Thread.CurrentThread.Priority = ThreadPriority.Lowest;

Also, I don't think you really want to cap it. If the machine is otherwise idle, you'd like it to get busy on with the task, right? ThreadPriority helps communicate this to the scheduler.

like image 90
dpurrington Avatar answered Sep 25 '22 12:09

dpurrington