保持CPU使用率低一段时间。 C#

时间:2013-08-05 14:54:01

标签: c# cpu-usage performancecounter

我有以下代码,只允许我的应用程序在CPU使用率低于一定时间后打开。但我只是需要一些帮助来添加一些东西,确保使用率保持这么低至少5秒,这样我就可以避免CPU使用率出现任何下降。

cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
var usage = cpuUsage.NextValue();
do
{
    Thread.Sleep(TimeSpan.FromSeconds(1));
    usage = cpuUsage.NextValue();
    Console.WriteLine(usage + "%");
} while (usage > 10.00);

Process proc = new Process();
proc.StartInfo = new ProcessStartInfo(@"C:\Documents and Settings\rcgames\Desktop\Game1.exe");
proc.Start();

1 个答案:

答案 0 :(得分:1)

int secondsWhileLowUsage = 0;     
do {
    cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    var usage = cpuUsage.NextValue();
    do
    {
        Thread.Sleep(TimeSpan.FromSeconds(1));
        usage = cpuUsage.NextValue();
        if (usage > 10.00)
            secondsWhileLowUsage = 0;

        Console.WriteLine(usage + "%");
    } while (usage > 10.00);
    secondsWhileLowUsage ++; 
} while (secondsWhileLowUsage < 5)

Process proc = new Process();
proc.StartInfo = new ProcessStartInfo(@"C:\Documents and Settings\rcgames\Desktop\Game1.exe");
proc.Start();