.NET 线程。如何限制处理器时间的使用
是否有任何方法可以减少 .NET 环境中非主线程的处理器时间使用。该线程始终用于从网络服务器获取信息,它会消耗所有单核处理器时间。我知道我可以使用 Thread.Sleep() 但对于此任务来说这似乎不是一个很好的解决方案。
Is there any methods to reduce processor time usage for a non-main thread in .NET environment. The thread is used for getting informaion from a web-server all the time and it consumes all one-core processor time. I know I can use Thread.Sleep() but it doesn't seem a nice solution for this task.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
搞乱优先顺序等等是行不通的。如果你的系统中有 1 个线程说“我有工作要做,让我工作”,并且没有其他竞争线程,Windows 将继续调度它。
您表明该线程正在从 Web 服务器获取信息。据推测,它至少在等待服务器响应时处于阻塞状态,因此希望当时不使用 CPU。不幸的是,听起来确实像是您正在轮询信息,因此 Thread.Sleep 在这里可能是最好的 - 除非有其他一些带外信号可以告诉线程何时应该下次轮询。
如果 Web 服务器“知道”线程下次轮询的时间,则有望对其进行修改以在其响应中包含此类信息。然后,您可以从响应中提取该信息,并至少将您的睡眠时间设置为适当的值。
或者,如果另一个线程将从其他地方获取指示应发出新请求的信息,那么您应该使用事件(例如
AutoResetEvent
),以及WaitOne
对该信号,再次指定合适的睡眠时期。这样,每当他们认为轮询应该再次发生时,其他东西就可以唤醒这个睡眠线程。Messing with priorities, etc, will not work. If you have 1 thread in your system that's saying "I've got work to do, let me work", and no other competing threads, windows will keep scheduling it.
You indicate that this thread is getting information from a web server. Presumably, it's at least blocking whilst waiting for a response from the server, so hopefully not using CPU at that time. Unfortunately, it does sound like you're polling for information, so
Thread.Sleep
may be best here - unless there's some other out of band signal that could tell the thread when it should next poll.If the web server "knows" when the thread should next poll, it could hopefully be modified to include such information in its responses. You could then extract that information from the response, and at least set your
Sleep
periods to an appropriate value.Alternatively, if another thread will obtain information from elsewhere that indicates that a new request should be issued, then rather than
Thread.Sleep
, you should use an Event (e.g.AutoResetEvent
), andWaitOne
on that signal, again specifying a suitable sleep period. That way, something else can awaken this sleeping thread whenever they think polling should again occur.您可以修改后台线程的优先级
You can modify the priority of the background threads