2011-04-25 23 views
0

我在尝试使用进度条显示当前CPU和内存使用情况时出错。该代码似乎是正确的,因为它与标签一起工作,但我收到一个错误“无法转换为int”,那么如何将性能计数器的数据转换为int以便它可以显示在进度条中?我尝试使用System.Convert.ToInt32(cpuCounter);,但它没有为我工作。这里是我的代码:如何将性能计数器的输出转换为int中的int

PerformanceCounter ramCounter; 
     ramCounter = new PerformanceCounter("Memory", "Available MBytes"); 
     ramCounter.NextValue(); 
     progressBar1.Value = ramCounter; 

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

谢谢!

回答

2

您需要结果PerformanceCounter.NextValue() - 你目前忽略它:

float value = cpuCounter.NextValue(); 
progressBar2.Value = (int) value; 

你要检查,当然预期值的范围 - 你可能想扩展它。

另一种选择是使用RawValue属性,它是一个long

+0

太好了!谢谢。你是对的,我确实需要扩展输出,但我对如何做到这一点毫无头绪:(任何想法?:) – llk 2011-04-25 10:19:52

+0

@Shadowalker:你需要给我们更多的信息 - 基本上解决你想要的输出范围成为,输入范围是什么,然后适当地相乘和相加。 – 2011-04-25 11:05:42

0

您不应该将性能计数器实例指定给您的进度条,而是将其值指定给您的进度条。该值本身是Int64。

progressbar1.Value = (Int32) ramCounter.RawValue; 

你的, 阿洛伊斯·克劳斯