【发布时间】:2017-02-16 10:20:11
【问题描述】:
我需要 Windows 服务中的一个线程来持续监控 CPU 使用率(可能每 5 秒)。如果 CPU 使用率低,则应激活其他线程。
我从SO Question 中找到了一个示例 CPU 使用情况监控代码(在我的帖子下面也给出了)。这是控制台应用程序的代码,为了保持Timer 活着,这个人最后使用Console.ReadLine();。
CPU 使用率控制台应用程序:
using System;
using System.Diagnostics;
using System.Timers;
using System.Threading;
using System.Collections.Generic;
namespace CPUPerformanceMonitor
{
class MonitoringApplication
{
protected static PerformanceCounter cpuCounter;
protected static PerformanceCounter ramCounter;
public static void TimerElapsed(object source, ElapsedEventArgs e)
{
float cpu = cpuCounter.NextValue();
float ram = ramCounter.NextValue();
Console.WriteLine(string.Format("CPU Value: {0}, ram value: {1}", cpu, ram));
}
public static void Main()
{
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
try
{
System.Timers.Timer t = new System.Timers.Timer(1200);
t.Elapsed += new ElapsedEventHandler(TimerElapsed);
t.Start();
Thread.Sleep(10000);
}
catch (Exception e)
{
Console.WriteLine("catched exception");
}
while (true) //Another sample BAD way to keep the timer alive
{ }
//Console.ReadLine(); //just to keep the time alive
}
}
}
问题:如何在 Windows-Service 应用程序中实现它。我的意思是,我如何让线程保持活力。
我的 Windows 服务结构:
我调用了一个线程回调方法OnStart()。此线程回调方法调用类CPUMonitor 的StartCPUMonitorinig() 方法(其中包含Timer 的代码)。
public void CPUMonitorinigThreadCallback()
{
//If nothing is there in this function, the thread will start up and then immediately shutdown. To deal with this situation, use "_shutdownEvent"
//The while loop checks the ManualResetEvent to see if it is "set" or not.
while (!_shutdownEvent.WaitOne(0))
{
// Replace the Sleep() call with the work you need to do
//Sleep(1000);
objCPUMonitor.StartCPUMonitorinig();
}
}
【问题讨论】:
-
我认为您以错误的方式处理此问题。听起来您基本上是在尝试完成一些工作,但前提是 CPU 利用率较低。您是否考虑过可以简单地降低工作线程的优先级(后台、空闲等)?如果我误解了你的意图,你能否给我更广泛的了解你想要达到的目标(总体而言)?
-
为什么需要线程。您可以使用计时器每 5 秒触发一次。
-
Windows 服务线程不进入睡眠状态。你基本上不需要做任何事情它会保持活力,只要你注册事件,它们就会被提升\
-
@ManfredRadlwimmer:你是对的。我有一个线程可以持续监控是否插入了 USB 记忆棒。当且仅当 CPU 使用率低时,我才需要从 USB 复制文件。大图:USB一插入就开始监控CPU使用率,当CPU使用率低时复制文件。
-
那么 Manfred 是对的——只是降低工作线程的优先级。
标签: c# multithreading timer windows-services