Reputation: 2145
I want to display a modal dialog with a progress bar while doing some work on the main UI Thread. Without using any multi-threading technique my UI would for sure be in a hanging state.
How do I achieve this while running the computationally intensive long operation on the main thread (as it involves UI elements and I shudder to touch this legacy code), while displaying the status of the computation on the wait window (which shall run on a different thread)
I need to run a progress dialog window on a different thread while keeping the main thread occupied to compute the long bound operation involving main UI form elements.
Thanks for some pointers
Upvotes: 0
Views: 1939
Reputation: 428
If your problem is updating status(progress bar) to the user while running that long task, then the solution is In Control.CheckForIllegalCrossThreadCalls = false
community advice's not to set that property to false, but i love to access all controls from any thread and it works fine and it's strait-forward, unless someone gives us a good reason not to use it other than "it's bad use Invoke instead".
private void button1_Click(object sender, EventArgs e) {
//To avoid Cross-thread exception
Control.CheckForIllegalCrossThreadCalls = false;
//Start background task
bkg.RunWorkerAsync();
//show wait form
var frmWait = new WaitForm();
frmWait.ShowDialog();
}
private void bkg_DoWork(object sender, DoWorkEventArgs e) {
//Do your work and update status
}
Upvotes: 1
Reputation: 1428
Its technically possible to create a Model Dialog on a thread other than UI thread (but certainly not advisable)
Anyway, since you cant change the legacy code, and want the model dialog to work on another thread, here is a suggestion
1> Create & open the Model dialog on separate thread
2> The Computation intensive work must be firing some event that would hook to report progress. These events are being fired from UI thread and you have to marshal them to the thread which created this model dialog. use Control.InvokeRequired
to detect that the call stack is from another thread & use control.Invoke(action)
to marshal it
Upvotes: 0
Reputation: 9461
UI can not be run in different thread. It should run in UIThread. You'll have to rewrite intense operations in different thread and pass parameters to it using dispatcher (since UI elements are accessible from UI Thread as I mentioned). If you block main thread you won't be able to show progress.
Upvotes: 1