C#Auto Cpu Usage刷新

时间:2013-12-10 15:19:42

标签: c#

我有这段代码:

 private void button1_Click(object sender, EventArgs e)
    {
        PerformanceCounter cpuCounter = new PerformanceCounter();
        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";
        PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
        var unused = cpuCounter.NextValue(); // first call will always return 0
        System.Threading.Thread.Sleep(1000);

        label1.Text = "Cpu usage: :" + cpuCounter.NextValue() + "%";
        label2.Text = "Free ram : " + ramCounter.NextValue() + "MB";
    }

写入程序的内容会自动更改%CPU利用率,而不是按一个按钮?

2 个答案:

答案 0 :(得分:1)

如果您想为特定ButtonClick模拟interval个活动,可以使用Timer控件。

第1步:您需要订阅Timer Tick活动 第2步:Interval的{​​{1}}属性设置为1000毫秒,以便每1秒举起一次事件。
第3步:Timer中只需致电Tick Event Handler事件处理程序 第4步:只要您想停止计时器,就可以调用Button Click方法。

试试这个:

timer1.Stop()

答案 1 :(得分:1)

您需要使用Timer重新执行任务。另外要解决“第一次调用将始终返回0”的问题,只需重新使用相同的性能计数器,每次调用定时器。

public MyForm()
{
    InitializeComponent();

    cpuCounter = new PerformanceCounter();
    cpuCounter.CategoryName = "Processor";
    cpuCounter.CounterName = "% Processor Time";
    cpuCounter.InstanceName = "_Total";
    ramCounter = new PerformanceCounter("Memory", "Available MBytes");


    //It is better to add the timer via the Design View so it gets disposed properly when the form closes.
    //timer = new System.Windows.Forms.Timer();

    //This setup can be done in the design view too, you just need to call timer.Start() at the end of your constructor (On form load would be even better however, ensures all of the controls have their handles created).
    timer.Interval=1000;
    timer.Tick += Timer_Tick;
    timer.Start();
}

//private System.Windows.Forms.Timer timer; //Added via Design View

private PerformanceCounter cpuCounter;
private PerformanceCounter ramCounter;


private void Timer_Tick(object sender, EventArgs e)
{
    label1.Text = "Cpu usage: :" + cpuCounter.NextValue() + "%";
    label2.Text = "Free ram : " + ramCounter.NextValue() + "MB";
}