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

回眸只為那壹抹淺笑 提交于 2019-11-29 06:17:29

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.

You can slow down a loop by calling Thread.Sleep(milliseconds) within the loop. That hands the CPU back to the scheduler.

But 'consuming too much CPU' makes me think you might have more fundamental problems. Is this thread polling and waiting for something else? If so, you should consider the use of Events or some other kernel-based signalling mechanism.

I guess you need to query some kind of OS API to find out how much of the CPU are you consuming and take throttling decisions (like Thread.Sleep) from that on.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!