There is a component for building graphs. It is required that 3 threads be added to this graph by function, and then points are added to the data array.
The problem is that I can not synchronize these actions. Whatever I do - use lock or Monitor , the threads still perform in disarray. As a result, I always get ArgumentOutOfRangeException - either the collection of graphs is not full, or the collection of graph data is not full. I have no more ideas.
Main form code:
public partial class Form1 : Form { delegate double MathFunc(double x); MathFunc [] functions = new MathFunc[] { Math.Sin, Math.Cos, Math.Tan }; Color[] colors = new Color[] { Color.Red, Color.Blue, Color.Green }; object obj = new object(); public Form1() { InitializeComponent(); //lineChart1.YTitle = "yyyyyyy"; //lineChart1.XMin = -5; //lineChart1.XMax = 10; lineChart1.YMax = 5; lineChart1.YMin = -5; for(int i=0; i<3; i++) { Thread thread = new Thread(ThreadFunc); thread.Start(i); } } private void ThreadFunc (object i) { int ii = Convert.ToInt32(i); if (lineChart1.InvokeRequired) { lock (obj) { LineChart.Curve curve = new LineChart.Curve(new List<PointF>(), new Pen(colors[ii], 2.0f)); lineChart1.BeginInvoke(new Action<LineChart.Curve>(lineChart1.Curves.Add), curve); for (int j = 0; j <= 100; j++) { float x = 0.1f * j; lineChart1.BeginInvoke(new Action<PointF>(lineChart1.Curves[ii].Data.Add), new PointF(x, (float)functions[ii](x))); } } } } }
BeginInvokejust puts the operation in a queue for execution in the UI stream, and does not wait for it to complete, yourlock (obj)absolutely useless. I propose to prepareLineChart.Curvetogether withDatain advance (in the background thread), and inBeginInvoketo send an already fully formed curve. - RaiderLineChart? - Byulent