为了账号安全,请及时绑定邮箱和手机立即绑定

如何获得C#中的CPU使用量?

如何获得C#中的CPU使用量?

C#
慕标琳琳 2019-06-28 16:35:52
如何获得C#中的CPU使用量?我希望得到C#中应用程序的总CPU使用量。我已经找到了很多方法来深入了解进程的属性,但是我只想要进程的CPU使用情况,以及像TaskManager中那样的CPU总量。
查看完整描述

3 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

比所要求的稍多一点,但是我使用额外的计时器代码来跟踪和警告CPU使用率在持续1分钟或更长时间内是否达到90%或更高。

public class Form1{

    int totalHits = 0;

    public object getCPUCounter()
    {

        PerformanceCounter cpuCounter = new PerformanceCounter();
        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";

                     // will always start at 0
        dynamic firstValue = cpuCounter.NextValue();
        System.Threading.Thread.Sleep(1000);
                    // now matches task manager reading
        dynamic secondValue = cpuCounter.NextValue();

        return secondValue;

    }


    private void Timer1_Tick(Object sender, EventArgs e)
    {
        int cpuPercent = getCPUCounter();
        if (cpuPercent >= 90)
        {
            totalHits = totalHits + 1;
            if (totalHits == 60)
            {
                Interaction.MsgBox("ALERT 90% usage for 1 minute");
                totalHits = 0;
            }                        
        }
        else
        {
            totalHits = 0;
        }
        Label1.Text = cpuPercent + " % CPU";
        Label2.Text = getRAMCounter() + " RAM Free";
        Label3.Text = totalHits + " seconds over 20% usage";
    }}


查看完整回答
反对 回复 2019-06-28
  • 3 回答
  • 0 关注
  • 837 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信