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))); } } } } } 

The project code is entirely here .

  • If you put the necessary part of the code in question, those people who are too lazy to download the project and understand it, will also be able to help. - VladD
  • @VladD But what if it is not in the part of the code that I thought about, and the error lies further? - Byulent
  • It certainly can be. But to understand the entire project will want, believe me, a much smaller number of participants. - VladD
  • Since BeginInvoke just puts the operation in a queue for execution in the UI stream, and does not wait for it to complete, your lock (obj) absolutely useless. I propose to prepare LineChart.Curve together with Data in advance (in the background thread), and in BeginInvoke to send an already fully formed curve. - Raider
  • @Raider, but what if you need to draw a curve in pieces? It is necessary to somehow illustrate the joint work of streams ... Or for this you have to redesign the entire LineChart ? - Byulent

0