Reputation: 3
My main form is performing long operations.In order to tell the user that the application is processing and not freezing I wanted to implement a progress bar in another form.
It seems that you can't interact with controls if you're not on the main thread. I tried to implement backgroundworker as suggested in the link below but without success.
http://perschluter.com/show-progress-dialog-during-long-process-c-sharp/
Same thing with Task-based Asynchronous Pattern
How to update the GUI from another thread in C#?
The closer to success I've been is with encapsulating the call of the progress bar form in another thread :
Form_Process f_p = new Form_Process();
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
// Create and show the Window
f_p.ShowDialog();
// Start the Dispatcher Processing
System.Windows.Threading.Dispatcher.Run();
}));
// Set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// Make the thread a background thread
newWindowThread.IsBackground = true;
// Start the thread
newWindowThread.Start();
f_p.label_Progression.Text = "Call to exe";
f_p.progressBar1.Value = 30;
f_p.Refresh();
But when I call a function in the main thread and I try to update the progress bar, the cross-thread exception is logically lifted.
Am I missing something ?
Upvotes: 0
Views: 130
Reputation: 1038
You can't set control properties on a form from a different thread. You need an invokation to do this.
On your form, create a function:
public void SetProgressText(string value) {
if (this.InvokeRequired) {
Action<string> progressDelegate = this.SetProgressText;
progressDelegate.Invoke(value);
} else {
label_Progression.Text = value;
}
}
And then, instead of
f_p.label_Progression.Text = "Call to exe";
call
f_p.SetProgressText("Call to exe");
Same for the progress bar. You can put all invokations inside one function though.
Upvotes: 1