如何在WPF中制作实时图表

时间:2015-09-01 13:36:22

标签: wpf charts

我试图在WPF中显示CPU使用率。如何刷新图表?

    private void populateCPUInfo()
    {
        try
        {
            LineSeries lineSeries1 = new LineSeries();
            lineSeries1.Title = "Title";
            lineSeries1.DependentValuePath = "Value";
            lineSeries1.IndependentValuePath = "Key";
            List<KeyValuePair<int, int>> l1 = new List<KeyValuePair<int, int>>();

            Thread thread = new Thread(new System.Threading.ThreadStart(delegate()
            {
                try
                {
                    PerformanceCounter theCPUCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                    PerformanceCounter theMemCounter = new PerformanceCounter("Memory", "Available MBytes");
                    float cpuUsage = 0.00F;
                      int xaxix = 1;
                    theCPUCounter.NextValue();
                    List<KeyValuePair<int, int>> valueList = new List<KeyValuePair<int, int>>();
                    CpuDataPoints cp1=new CpuDataPoints();
                    cp1.value = new KeyValuePair<int, int>(xaxix++, Convert.ToInt32(cpuUsage));
                    lineSeries1.ItemsSource = l1;
                    cpuUsageChart.Series.Add(lineSeries1);

                    while (iscontinue)
                    {
                        cpuUsage = theCPUCounter.NextValue();
                        l1.Add( new KeyValuePair<int, int>(xaxix++, Convert.ToInt32(cpuUsage)));

                        Thread.Sleep(450);
                    }
                }
                catch (Exception ex)
                {
                }
            }));

            thread.Priority = ThreadPriority.Highest;
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();//Start the Thread
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
    }
}

1 个答案:

答案 0 :(得分:0)

对图表的ObservableCollection使用ItemsSource,而不是List。它将为您处理UI更新通知:

ObservableCollection<KeyValuePair<int, int>> l1 = new ObservableCollection<KeyValuePair<int, int>>();