我正在尝试从线程中将 CPU 使用率更新到进度条上。
我这里的代码是:
private static int _cpuUsage;
protected PerformanceCounter cpuCounter;
private Thread thread;
public CPUUsageIndModel()
{
cpuCounter = new PerformanceCounter
{CategoryName = "Processor", CounterName = "% Processor Time", InstanceName = "_Total"};
thread = new Thread(GetCurrentCpuUsage);
thread.Start();
}
public void GetCurrentCpuUsage()
{
while (true)
{
_cpuUsage = Convert.ToInt32(Math.Round(cpuCounter.NextValue()));
Thread.Sleep(1000);
}
}
public int GetCPUUsage
{
get { return _cpuUsage; }
set
{
_cpuUsage = value;
NotifyPropertyChanged("_cpuUsage");
}
}
现在问题是我已经尝试使用以下方法启动线程:
public void GetCurrentCpuUsage()
{
_cpuUsage = 40;
}
它工作正常,所以留下了cpuCounter
and 循环使用。
谁能指出我可能犯的任何错误。
谢谢
编辑 - 完成课程和一些小调整:
public class CPUUsageIndModel : INotifyPropertyChanged
{
public static int _cpuUsage;
protected PerformanceCounter cpuCounter;
private Thread thread;
public CPUUsageIndModel()
{
cpuCounter = new PerformanceCounter
{CategoryName = "Processor", CounterName = "% Processor Time", InstanceName = "_Total"};
thread = new Thread(GetCurrentCpuUsage);
thread.Start();
}
public void GetCurrentCpuUsage()
{
while (true)
{
CPUUsage = Convert.ToInt32(Math.Round(cpuCounter.NextValue()));
Thread.Sleep(1000);
}
}
public int CPUUsage
{
get { return _cpuUsage; }
set
{
_cpuUsage = value;
NotifyPropertyChanged("_cpuUsage");
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}