Fair warning here, I'm new to C# and Windows forms, so I may be approaching this the wrong way. I have an application that is computing live data points that needs to be added to my Windows Form's chart series. This data is computed as frequently as every 10 milliseconds and needs to be updated close to this rate, preferably within +50 milliseconds.
The Forms application and chart are built with the graphical builder contained within visual studio, as such the source files generated have an auto generated warning not to modify them: do not modify the contents of this method with the code editor.
What I have done is made the chart Public with the properties modifier so I can access it in my code. In my main program, I'm atempting to do something like this:
static Form1 form;
Series series = new Series();
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form = new Form1();
new UpdateLoop.Start();
Application.Run(form);
}
void Start() {
series.ChartArea = "ChartArea1";
series.ChartType = SeriesChartType.Line;
series.Legend = "Legend1";
series.Name = "Test series";
series.Points.Add(new DataPoint(0D, 0D)); //add start point
}
void tElapse(object sender, ElapsedEventArgs e) { //this is called every 10 miliseconds
double points[] = ...; //get points from elsewhere
for(int i = 0 ; i < points.Count; i+=2) {
series.Points.Add(new DataPoint(points[i], points[i+1]));
}
}
}
What happens when I run this is that it adds the starting point just fine, creates the chart, But, it only manages to add about 1-2 points before it gives me a System.InvalidOperationException
and warns me that I'm making a cross-thread operation on the Control chart1 (my chart). Clearly, I shouldn't be adding data from a different thread this way. However, I need a way to do this. How can I?
ps: I know Java has synchronized (which I don't really know how to use) for cross thread operations, does C# have a similar sort of thing?
edit: forgot to mention: I must have this on two threads, I don't want the graphics thread running the main program also. Plus, I'm fairly certain that is bad practice anyways.