最好的方式来编码PerformanceCounters

最好的方式来编码PerformanceCounters

问题描述:

我正在做一个窗体,显示性能数据,我有几个性能计数器,显示有关处理器和内存的一些信息。由于第一个结果总是“0”,我在分配下一个值之前正在执行睡眠线程。这样做的问题在于,它确实使程序呆滞。最好的方式来编码PerformanceCounters

即使移动窗口也很慢,我敢打赌,它是由于线程睡眠事件,它基本上是每秒运行一次。我将定时器设置为始终启用,间隔为1秒,因为我希望它显示“实时”类型的信息。

这是到目前为止我的代码:

private PerformanceCounter pcProcess; //Process 
    private PerformanceCounter pcMemory; //Memory 

    private void tmrProcess_Tick(System.Object sender, System.EventArgs e) 
    { 
     pcProcess = new PerformanceCounter(); //New Performance Counter Object 
     pcProcess.CategoryName = "Processor"; //Specify Process Counter 
     pcProcess.CounterName = "Interrupts/sec"; 
     pcProcess.InstanceName = "_Total"; 
     pcProcess.NextValue(); 
     System.Threading.Thread.Sleep(1000); 
     cpInt.Text = pcProcess.NextValue().ToString(); //Display 
     pcProcess.CounterName = "% Processor Time"; 
     pcProcess.InstanceName = "_Total"; 
     pcProcess.NextValue(); 
     System.Threading.Thread.Sleep(1000); 
     cpPower.Text = pcProcess.NextValue().ToString() + "%"; //Display 
    } 

    private void tmrMemory_Tick(System.Object sender, System.EventArgs e) 
    { 
     pcMemory = new PerformanceCounter(); 

     pcMemory.CategoryName = "Memory"; 
     //This counter gives a general idea of how many times information being requested is not   where the application (and VMM) expects it to be 
     pcMemory.CounterName = "Available MBytes"; 
     avlMem.Text = pcMemory.NextValue().ToString() + " Mb"; 
     pcMemory.CounterName = "Page Faults/sec"; 
     pcMemory.NextValue(); 
     System.Threading.Thread.Sleep(1000); 
     pgFaults.Text = pcMemory.NextValue().ToString(); 
    } 

如果计数器的计算值取决于两个计数器读操作, 第一个读操作返回0.0。重置性能计数器 属性以指定不同的计数器相当于创建 新的性能计数器,并且使用新的 属性的第一个读取操作返回0.0。 NextValue方法调用 之间的建议延迟时间为1秒,以允许计数器在下一次增量读取时执行 。

所以基本上:

private PerformanceCounter pcMemory; 

private void InitPerfmon() 
{ 
    this.pcMemory = new PerformanceCounter(); 
    this.pcMemory.CounterName = "Available MBytes"; 
    this.pcMemory..... 
    ... 
    this.pcMemory.NextValue(); 
} 

private void tmrMemory_Tick(System.Object sender, System.EventArgs e) 
{ 
    this.pgFaults.Text = this.pcMemory.NextValue().ToString(); 
} 
+0

我应该拨打的PerformanceCounter两次?所以它会是this.pcMemory = new PerformanceCounter this.pcProcess = new PerformanceCounter(); – user263029 2014-10-03 13:53:47

+0

@ user263029是的,您应该为每个您正在监控的计数器提供一个实例 – ken2k 2014-10-03 14:35:28