//button is clicked
//worker starts
private void processWorker_DoWork(object sender, DoWorkEventArgs e)
{
string code = DoLongWorkAndReturnCode();
if (code != 0)
{
MessageBox.Show("Error!");
EnableAllButtons(); // this is defined in the other thread and it's where i run into the error.
}
else
{
string code = DoAnotherLongProcessAndReturnCode();
if (code != 0)
{
MessageBox.Show("Error 2!");
EnableAllButtons(); // again, this is defined in the other thread
}
}
}
I’m running into a cross threading error because “EnableAllButtons()” is defined in a different thread.
How do I go about enabling all buttons in one thread, from a different thread?
Based on your names I am assuming you are using a BackgroundWorker. You must either update your controls in ProgressChanged, RunWorkerCompleted, Control.Invoke or Control.BeginInvoke (You do not need to fire EndInvoke for Control’s BeginInvoke).
My recommendation is throw a exception in your background worker (if you are not using code other than checking for 0, if not use the Result method.) and check the Error property of the parameter passed in to the RunWorkerCompleted event. From there you can spin up another background worker or stop. you will be running on the main thread so you can change your buttons without invoking.
Example: Enabling the buttons via BeginInvoke
With this example you can use your code as is just modify EnableAllButtons
Example: Returning data via Result
Example: Returning data via Exception + reusing event handlers.