how to use thread to control chart?
-
Hello,when i start thread to plot in chart,but form is lose control, looks like thread is not in use. private void button1_Click(object sender, EventArgs e) { Thread th=new Thread(new ThreadStart(fun1)); th.Start(); } void fun1() { base.Invoke((MethodInvoker)delegate{ Series series1 = new Series(); for (int i = 0; i < 300; i++) { series1.Points.Add(new DataPoint(i, i)); Thread.Sleep(1000); } chart1.Series.Add(series1); }); }
-
Hello,when i start thread to plot in chart,but form is lose control, looks like thread is not in use. private void button1_Click(object sender, EventArgs e) { Thread th=new Thread(new ThreadStart(fun1)); th.Start(); } void fun1() { base.Invoke((MethodInvoker)delegate{ Series series1 = new Series(); for (int i = 0; i < 300; i++) { series1.Points.Add(new DataPoint(i, i)); Thread.Sleep(1000); } chart1.Series.Add(series1); }); }
Ohm the thread works. The problem is that the code you're Invoking is being executed on the UI thread, not the thread you launched, because, well, THAT'S WHAT INVOKE DOES! And then you put the UI thread to sleep for a second. Once the Sleep is done and the delegate is done running, THEN you UI thread can get back to processing the message pump, like responding to WM_PAINT messages to repaint your window if needed. You cannot touch a UI control properties or methods from anything other than the UI thread. You can create a new Series object and populate it with data in the background thread and THEN make the assignment to the chart object in delegated code. You're doing everything in the delegate, on the UI thread.
A guide to posting questions on CodeProject
Click this: Asking questions is a skill. Seriously, do it.
Dave Kreskowiak