0

我正在尝试从线程中将 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;
}

它工作正常,所以留下了cpuCounterand 循环使用。

谁能指出我可能犯的任何错误。

谢谢

编辑 - 完成课程和一些小调整:

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
    }
4

2 回答 2

1

您需要将更改通知 WPF 运行时。为此,您实现INotifyPropertyChanged接口。

您似乎在这里尝试过,但是您没有以正确的方式进行操作(您没有显示所有相关代码,但我相当确定您的实现不正确)。

您需要: 1. 绑定到公共属性(我们在您粘贴的代码中没有看到这一点) 2. 如果值发生更改,则从属性的设置器发送通知 3. 通过属性设置器更改值

您可能正确地执行了第一点,我们没有看到这一点,但是您正在通知私有字段已更改,并且您应该通知该属性已更改(NotifyPropertyChanged("GetCPUUsage"))。您还可以通过直接访问字段 ( _cpuUsage = 40;) 来设置值,并且应该通过 setter ( GetCPUUsage = 40;) 来完成。

在这种情况下,您的属性名称有点奇怪。我将重命名GetCPUUsageCPUUsage,因为您可以获取并设置它的值。前缀Get也应该用于方法,而不是属性。

于 2012-07-31T21:26:46.680 回答
1

看起来你几乎是对的,至少从编辑来看。只是,您正在提高字段名称而不是属性名称上更改的属性。这是修复:

public int CPUUsage
        {
            get { return _cpuUsage; }
            set
            {
                _cpuUsage = value;
                NotifyPropertyChanged("CPUUsage"); // Notify CPUUsage not _cpuUsage
            }
        }

你的绑定应该看起来像 {Binding Path=CPUUsage}

于 2012-07-31T21:40:51.003 回答