Possible Duplicate:
Cross-thread operation not valid
I have a problem with using of threading in my application below are the two simple methods and this two methods are called on a button click.
I want to first run the inserting method and thread sleep for 5 seconds after 5 seconds second method run and display according to the coding.
But I face this error:
Cross-thread operation not valid: Control ‘lblDisplay’ accessed from a thread other than the thread it was created on.
Here’s the code:
private void button1_Click(object sender, EventArgs e)
{
Thread obj = new Thread(new ThreadStart(inserting));
Thread obj1 = new Thread(new ThreadStart(insert));
obj.Start();
obj1.Start();
}
public void inserting()
{
lblDisplay.Text = "inserting record......";
Thread.Sleep(5000);
}
public void insert()
{
lblDisplay.Text = "Record successfully inserted";
}
You are getting the error because you cannot access UI elements on threads other than the main UI thread (or Dispatcher thread in WPF). If you wish to have some status update system, you would be better off having the process(es) running on a separate thread, that then call back onto the main UI thread to update the status text. For example:
Note: This is an answer specific to WinForms. For WPF, you use
CheckAccess()instead ofInvokeRequiredandthis.Dispatcher.BeginInvoke(...)instead ofBeginInvoke(...).