0

I have been getting the error message: "Collection was modified; enumeration operation may not execute." I was able to isolate, and reproduce the error with the code below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        Thread tester;
        int testNum = 0;

        public Form1()
        {
            InitializeComponent();

            tester = new Thread(threadTester);
            tester.IsBackground = true;
            tester.Start();

        }

        public void threadTester()
        {
            bool testWhile = true;

            while (testWhile)
            {
                Thread.Sleep(1);

                testNum++;

                updateChart();

            }
        }

        public void updateChart()
        {
            testChart.Series["Series1"].Points.AddXY(testNum, testNum);
        }
    }
}

After reading some other similar problems, I am guessing I am recieving this error because the program is trying to display/update the chart while simultaneously adding a datapoint to the chart collection.

I read that because I am adding points from a separate thread, I am supposed to use the Invoke method but I cannot figure out how to implement it correctly into my code.

I am hoping someone could put me on the right path to fix this issue.

Satchan
  • 1
  • 3
  • it's a [duplicate of this](https://stackoverflow.com/questions/844850/strange-collection-was-modified-after-the-enumerator-was-instantiated-exceptio) – Software Dev Jan 08 '18 at 04:24
  • You cannot update the UI from a non-UI thread. That's your major mistake. – Enigmativity Jan 08 '18 at 05:22
  • @zackraiyan - It's not a duplicate - this is a threading issue (which results in the error when the UI thread is trying to iterate the loop). – Enigmativity Jan 08 '18 at 05:24
  • 1
    @KenWhite - It's not a duplicate - this is a threading issue (which results in the error when the UI thread is trying to iterate the loop). – Enigmativity Jan 08 '18 at 05:24
  • Below should work.. please check for syntax this.testChart.BeginInvoke(delegate() { testChart.Series["Series1"].Points.AddXY(testNum, testNum); }); – Ashok Patel Jan 08 '18 at 05:44

0 Answers0