質問

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;  
        }
役に立ちましたか?

解決

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)))); 
}

他のヒント

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;
    });
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top