我試圖運行一個外觀來將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
和循環使用。
任何人都可以指出我可能犯的任何錯誤。
感謝
編輯 - 完整的類和一些小的調整:
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
}
你有沒有考慮的BackgroundWorker和ProgressChanged? – Paparazzi 2012-07-31 21:28:07