以编程方式限制在服务内运行的线程的 CPU 使用率 [英] Programmatically limit CPU Usage of a Thread running inside a Service

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

问题描述

我使用的是 VB9 (VS2008).

I'm using VB9 (VS2008).

我创建了一个 Windows 服务,它定期为一些文件夹编制索引.

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

有没有办法根据当前系统状态设置CPU使用率上限,即如果系统空闲,线程可以根据需要使用CPU,但如果有其他程序/processes 运行然后它应该以不会使系统变慢的方式使用 CPU.

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.

推荐答案

您可以通过 Thread.Priority

将其设置为BelowNormal"将意味着其他线程将被安排在它之前.

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.

请注意,由于您正在执行大量磁盘 IO,这实际上将是后台任务的主要影响,并且您可能会发现降低优先级是不够的(因为磁盘 IO 将继续部分,即使线程处于受到限制.

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.

检查机器使用情况的监控线程(可选择仅在至少有一个交互式用户存在时才关心)可以暂停索引(或显着限制 IO).这在有许多可用内核(和超线程虚拟内核)的现代机器上更为重要,这意味着尽管用户实际上做了很多工作,但仍然存在空闲资源来执行您的索引线程,而不是真正执行磁盘 IO.

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.

您可能还想考虑是否检查 Power方案确定你是否应该在那个时候运行(因为两个重磁盘访问的电池消耗不是微不足道的)

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)

如果您希望做更多的事情来减少从 Vista 开始的 Windows 后台 IO 绑定任务版本的影响,请添加两个有用的 API:

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:

这允许您的代码以比其他 I/O 更低的优先级调度 I/O.

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

您可以使用它来安排在系统空闲时间"运行的事情.当系统不忙且用户不在时.

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天全站免登陆