Reputation: 2203
I'm using the following code to disable form controls while i'm doing some longTask() thread. But the controls are not getting disabled.. Here is my code for disable() method.
public void disableFormControls()
{
if (InvokeRequired)
{
this.BeginInvoke(new Action(disableFormControls));
return;
}
groupBoxInput.Enabled = false;
groupBoxOutput.Enabled = false;
btnGen.Enabled = false;
btnReset.Enabled = false;
}
Here is how i'm calling it.. NOTE: LongTask() will be running in a separate thread.
private void LongTask()
{
disableFormControls();
Console.WriteLine("Started Records::" + DateTime.Now);
//Doing my long tasks here
enableFormControls();
}
Can you please let me know where i'm wrong..
Upvotes: 0
Views: 555
Reputation: 4996
To make sure you're executing your code on the UI thread synchronously, please use Invoke
instead of BeginInvoke
.
Upvotes: 1
Reputation: 24413
You have two choices here as you can cannot modify winform UI controls from non UI thread
You can move the enable/disable UI code back to the UI thread. Before starting the task disable the controls in the UI thread and use the dispatcher to enable them back in the UI thread at task completion.
You can use data binding to bind the enable state of these controls to some no UI object that you can freely modify from any thread.
Upvotes: 1
Reputation: 1075
Try this, I changed the Invoke of enableForm
to instead call disableFormControls
. Also I did this synchronously instead of asynchronously so your background thread isn't doing anything until the UI is updated properly. I'm also assuming disableFormControls
is a method on your Form.
public void disableFormControls()
{
if (InvokeRequired)
{
this.Invoke(new Action(disableFormControls));
return;
}
groupBoxInput.Enabled = false;
groupBoxOutput.Enabled = false;
btnGen.Enabled = false;
btnReset.Enabled = false;
}
Upvotes: 4