Question

I am trying to keep updating my linechart according to the updated information in my application but it keeps returning the error InvalidOperationException.

The code works fine if I input static information. My codes as follows. Appreciate any help. Thanks.

CPUEvent is firing off every second. CurrentCPU is the value of the cpu every second. This information is updated every second.

List<KeyValuePair<double, double>> cpuList = new List<KeyValuePair<double, double>>(); 
public int counter = 0; 

public MainWindow()
        {
            InitializeComponent();
            CPUEvent += showChart; 
        }

private void showChart(object sender, CPUEventArgs args) //////
        {
            counter += 1;
            cpuList.Add(new KeyValuePair<double, double>(counter, args.CurrentCPU)); 
            lineChart.DataContext = cpuList;  
        }
Was it helpful?

Solution

If the goal is to update UI automatically after insertions or deletions, it is recommended to use the ObservableCollection class instead of resetting the DataContext property.

The code can be rewritten so:

ObservableCollection<KeyValuePair<double, double>> cpuList = new ObservableCollection<KeyValuePair<double, double>>(); 
public int counter = 0; 

public MainWindow()
{
    InitializeComponent();

    lineChart.DataContext = cpuList; 
    CPUEvent += showChart; 
}

private void showChart(object sender, CPUEventArgs args) //////
{
    counter += 1;
    Dispatcher.BeginInvoke((Action)(() => cpuList.Add(new KeyValuePair<double, double>(counter, args.CurrentCPU)))); 
}

OTHER TIPS

If CPUEvent is running on different thread (non UI thread) and if the exception was something about invalid cross thread operation exception, try to wrap codes accessing UI controls within Dispatcher.BeginInvoke() to make it executed from UI thread :

private void showChart(object sender, CPUEventArgs args)
{
    counter += 1;
    cpuList.Add(new KeyValuePair<double, double>(counter, args.CurrentCPU)); 

    Dispatcher.BeginInvoke(() =>
    {
        lineChart.DataContext = cpuList;
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top