For windows program using Threads or Task there is a common exception raised "Cross-thread operation not valid: Control '[UI Control Name]' accessed from a thread other than the thread it was created on"
The reason is due to multiple task or threading the the drawing object or UI control is accessed via different threads and which is not acceptable during runtime.
The common solution is to use INVOKE method.
A sample code example is given here with a very simple explanation:
private void button_action_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
AnyMethod(this.text_live_frequency, this.button_live_action);
});
}
private void AnyMethod()
{
System.Threading.Thread.Sleep(5);
//chart is ChartInfo type
chart.Invoke(new Action(() => { ChartRefreshLive(chart, time, chartCount); }));
//textbox
this.text_live_frequency).Invoke(new Action(() =>
{
this.text_live_frequency.Enabled = false;
}));
}
As AnyMethod is invoked from task factory, modifying the textbox or chart would raise an exception if the Invoke was called.
The above code will work as invoke method puts it to the original thread.
The reason is due to multiple task or threading the the drawing object or UI control is accessed via different threads and which is not acceptable during runtime.
The common solution is to use INVOKE method.
A sample code example is given here with a very simple explanation:
private void button_action_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
AnyMethod(this.text_live_frequency, this.button_live_action);
});
}
private void AnyMethod()
{
System.Threading.Thread.Sleep(5);
//chart is ChartInfo type
chart.Invoke(new Action(() => { ChartRefreshLive(chart, time, chartCount); }));
//textbox
this.text_live_frequency).Invoke(new Action(() =>
{
this.text_live_frequency.Enabled = false;
}));
}
As AnyMethod is invoked from task factory, modifying the textbox or chart would raise an exception if the Invoke was called.
The above code will work as invoke method puts it to the original thread.