编程限制服务中运行的线程的CPU使用情况 [英] Programmatically limit CPU Usage of a Thread running inside a Service

查看:126
本文介绍了编程限制服务中运行的线程的CPU使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用VB9(VS2008)。



我创建了一个Windows服务,用来索引某些文件夹定期。



有没有一种方法我可以把一个上限就取决于当前的系统状态的CPU占用率,也就是说,如果在系统空闲时,线程可以尽可能多的使用CPU,因为它需要,但如果有其他程序/运行,那么就应该使用方式的CPU不使系统缓慢的过程。


解决方案

您可以减少通过 Thread.Priority

将其设置为BelowNormal将意味着其它线程将在它的前面安排。



这会导致线程被饿死,但听起来好像这是你需要一个可以接受的设计决策。



请注意,由于要执行大量的磁盘IO这实际上将是主要影响回到地面的任务,你可能会发现,减少优先级是不够的(因为磁盘IO将继续甚至在线程节流部分。



一个监视线程该检查机的(任选仅关心当至少一个交互式用户存在)可以暂停索引(或相​​当节流IO)的用法。这将是在那里有很多可用的核心(和超线程虚拟内核),这意味着,尽管用户实际上做了很多工作备用资源的存在,以执行索引线程,但没有真正执行的磁盘IO现代机器更重要。



您可能还需要考虑你是否检查的电源使用方案,以确定是否应该在那个时候运行(因为从两个沉重的磁盘访问的电池消耗也是不可小视的)



如果你希望做更多,以减少从Vista的窗口此背景下IO势必任务版本的影响,开始加入​​了两个有用的API:



低优先级I / O



这可以让你的代码来安排I / Ø比其他I / O优先级较低。



Windows任务调度<​​/A>



您可以使用此安排的事情在系统空闲时间运行。此当系统不忙,而且用户不存在


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.

解决方案

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.

这篇关于编程限制服务中运行的线程的CPU使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆