表现计数器,显示0%

时间:2012-08-22 10:19:22

标签: c#

我遇到了问题:我的性能计划总是显示0%的CPU使用率......

我添加了一个名为Text value CPU的标签:

以下是代码:

public partial class Form1 : Form
{
    PerformanceCounter cpu = new PerformanceCounter ("Processor", "% Processor Time", "_Total");

    public Form1()
    {
        InitializeComponent();
        //string cpu_ussage =
        Text.Text = "CPU: " + CPU_TIME();
    }
    // Provjera Procesa koristeći %
    public string CPU_TIME()
    {
        float cpu_time;

        cpu_time = cpu.NextValue();
        return Math.Round(Convert.ToDouble(cpu_time.ToString()), 2) + "%";

    }
    private void timer1_tick(object sender, EventArgs e)
    {
      Text.Text = "CPU Time:" + CPU_TIME();
    }
}

2 个答案:

答案 0 :(得分:0)

您可以只用

替换
return cpu.NextValue();

答案 1 :(得分:0)

可能是因为在程序已经运行并且完成后正在读取CPU%,并且这个计数器实际为0.我试过你的例子,它确实打印了0.但是当你尝试下面的循环时你做了会看到价值观。

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;



namespace Stackoverflow
{
    public class PerfCounters
    {
        public static void Main()
        {
            var processorCategory = PerformanceCounterCategory.GetCategories()
                .FirstOrDefault(cat => cat.CategoryName == "Processor");
            var countersInCategory = processorCategory.GetCounters("_Total");
            DisplayCounter(countersInCategory
                .First(cnt => cnt.CounterName == "% Processor Time"));
            Console.Read();
        }
        private static void DisplayCounter(PerformanceCounter performanceCounter)
        {
            while (!Console.KeyAvailable)
            {
                Console.WriteLine("{0}\t{1} = {2}",
                    performanceCounter.CategoryName
                    , performanceCounter.CounterName
                    , performanceCounter.NextValue());
                Thread.Sleep(1000);
            }
        }
    }
}

HTH