I find OriginalGriff‘s alternative progress reporting method quite interesting. But I ran into a problem, which I suspect I also will run into if I use the BackgroundWorker.
My idea is to start a long task and ‘report’ progress from the start. But I only want to bring up a dialog window with the progress bar after a second or two. I designed a dialog class implementing the IProgress interface for this. Thus I will not have any progress bar window if the task didn’t take much time after all.
But with my task and the dialog running in different threads, I wasn’t allowed to show the dialog midway through my lengthy task.
Is there a solution to this? (Note: I’m a C# newbie, but experienced in other programming languages).
I find OriginalGriff‘s alternative progress reporting method quite interesting. But I ran into a problem, which I suspect I also will run into if I use the BackgroundWorker.
My idea is to start a long task and ‘report’ progress from the start. But I only want to bring up a dialog window with the progress bar after a second or two. I designed a dialog class implementing the IProgress interface for this. Thus I will not have any progress bar window if the task didn’t take much time after all.
But with my task and the dialog running in different threads, I wasn’t allowed to show the dialog midway through my lengthy task.
Is there a solution to this? (Note: I’m a C# newbie, but experienced in other programming languages).
WinForms and WPF have a rule that only the primary thread (the UI thread) is allowed to touch visual elements such as windows and progress bars. Since the job is done on a secondary thread, that thread may not update UI elements. Not directly, at least.
If you want to update a visual element from a worker thread, you use Invoke
(WinForms) or Dispatcher.Invoke
(WPF).
WinForms:
this.Invoke (() => {
progressForm.Show ();
progressBar.Value++;
});
WPF:
this.Dispatcher.Invoke (() => {
progressWindow.Show ();
progressBar.Value++;
});
ShowModal
) is generally bad thing (excluding several tradition cases such as file dialogs or About dialog). Doing anything with a dialog from a non-UI threads is even a lot worse. – Sergey A Kryukov Commented Jan 23 at 0:54