首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PerformanceCounter.GetNext()

使用PerformanceCounter.GetNext()
EN

Stack Overflow用户
提问于 2014-11-21 19:30:15
回答 2查看 249关注 0票数 0

有人能告诉我为什么这不管用吗。我猜想这与实例化或全局值有关。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.Speech.Synthesis;

namespace UtilApp
{
    class Perf
    {
        #region Performance Counters
        // CPU utilization
        PerformanceCounter CPU_Perf = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
        // Memory left
        PerformanceCounter MEM_Perf = new PerformanceCounter("Memory", "Available MBytes");
        // System Up time
        PerformanceCounter SYS_Perf = new PerformanceCounter("System", "System Up Time");
        #endregion

        public int getUsedCPU()
        {
            Console.WriteLine("Requested CPU Usage...");
            int v = (int) CPU_Perf.NextValue();
            Console.WriteLine("Value: {0}", v);
            return v;
        }

        public int getFreeMEM()
        {
            return (int) MEM_Perf.NextValue();
        }

        public int getUpTime()
        {
            return (int) SYS_Perf.NextValue();
        }
    }
}

基本上,当我知道不正确时,getUsedCPU()总是返回0。我从一个使用在线教程构建的控制台应用程序中复制了这些内容。

我从表单中访问它来显示CPU的使用情况.

代码语言:javascript
复制
Perf p = new Perf;
label1.text = p.getUsedCPU().toString();

注意: console.writeline是用于调试的,但在没有它们的情况下仍然获得0。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-21 19:35:17

来自MSDN

如果计数器的计算值依赖于两个计数器读取,则第一个读取操作返回0.0。

因此,如果您再次调用该方法,那么您将得到您正在寻找的方法。

此外,来自这里

若要获取用于执行必要计算所需的初始或先前值的计数器的性能数据,请两次调用NextValue方法并使用应用程序要求返回的信息。 为什么会发生这种事?

正如Jon在他的评论中提到的那样,这是因为OP每次都在创建一个新的Perf实例。

票数 4
EN

Stack Overflow用户

发布于 2014-11-21 19:43:38

添加类构造函数,然后创建对象的实例:

代码语言:javascript
复制
PerformanceCounter CPU_Perf;
PerformanceCounter MEM_Perf;
PerformanceCounter SYS_Perf;

public Perf()
{
        PerformanceCounter CPU_Perf = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
        PerformanceCounter MEM_Perf = new PerformanceCounter("Memory", "Available MBytes");
        PerformanceCounter SYS_Perf = new PerformanceCounter("System", "System Up Time");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27068874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档