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.