0

i wrote this code to create a chart(by using wpf toolkit charting) but I receive this error,

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        LoadLineChartData2();            
    }
    private void LoadLineChartData2()
    {
        time= new Timer(10);
        time.Elapsed += new ElapsedEventHandler(time_Elapsed);
        time.Start();
    }
    Timer time;
    List<KeyValuePair<double, int>> list = new List<KeyValuePair<double, int>>();
    int index = 0;
    void time_Elapsed(object sender, ElapsedEventArgs e)
    {
        list.Add(new KeyValuePair<double,int>(1.0/int.Parse(e.SignalTime.Second.ToString()),index++));
        this.Dispatcher.Invoke(new Action(()=> {
        ((System.Windows.Controls.DataVisualization.Charting.LineSeries)mcChart.Series[0]).ItemsSource = list;

        if (index>200)
        {
            time.Stop();
        }
        }));
    }       

erorr: Collection was modified; enumeration operation may not execute.

what is the error and how I can dynamically add points??

abdolah
  • 546
  • 1
  • 4
  • 13
  • search for " C# Collection was modified" - asked many times before. Please try searching first. – Mitch Wheat Jan 12 '14 at 04:52
  • for instance: first hit (and there are LOADS): http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute – Mitch Wheat Jan 12 '14 at 04:55

1 Answers1

1

Your list object is not thread-safe. I am assuming you are using a re-entrant timer as well. Your code will be executing in a new thread every 10 milliseconds, which presumably causes the List<> to be changed each time.

Try changing the time/tick (to maybe 100ms) and see if your problem goes away. You should also use a ConcurrentBag<T> in place of the list, which will support concurrent adds and iterations. Though I am going to add as an editorial comment, what you are trying to do in your code does not make sense to me.

theMayer
  • 15,456
  • 7
  • 58
  • 90