Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

c# - Programmatically limit CPU Usage of a Thread running inside a Service

I'm using VB9 (VS2008).

I've created a Windows Service that indexes some folders regularly.

Is there a way I can put an upper limit on the CPU usage depending upon the current system state, i.e., if the system is idle, the thread can use the CPU as much as it needs, but if there are other programs/processes running then it should use the CPU in way that does not make the system slow.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can reduce the priority of the thread, in .Net via Thread.Priority

Setting it to BelowNormal will mean that other threads will be scheduled in front of it.

This can lead to the thread being starved, but it sounds like this is an acceptable design decision for your needs.

Note that since you are performing considerable disk IO this actually will be the main impact of the back ground task, and you may find that reducing the priority is not sufficient (since the disk IO will continue in parts even while the thread is throttled.

A monitoring thread that checks the usage of the machine (optionally caring only when at least one interactive user is present) could pause the indexing (or throttle the IO considerably). This will be more important on modern machines where there are many available cores (and hyper threading virtual cores) which mean that despite the user actually doing a lot of work spare resources exist to execute your indexing thread but not really to execute the disk IO.

You may also want to consider whether you check the Power Scheme to determine if you should run at that time (since the battery drain from both heavy disk access is not inconsiderable)

If you wish to do even more to reduce the impact of this background IO bound task versions of windows from Vista onwards add two useful APIs:

Low Priority I/O

This allows your code to schedule I/O at a lower priority than other I/O.

Windows Task Scheduler

You can use this to schedule things to run at "system idle time". This when the system isn't busy, and the user is not present.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...