Srv19
Srv19

Reputation: 3618

Winforms application with forms in different threads

In the application i am working on, there are several forms; one used for the purposes of displaying 3d images, and other for governing that. Some changes in the images are time-consuming, and while they are going through, both of forms are not being redrawn.

What i would like to achieve is for at least controlling form (that is composed from fairly standard components only) to continue interaction with user and continue being redrawed. The way i see it, it should be moved into different thread, as the thread it is using now is too busy.

How should i do that? Wil Application.Run(secondForm) be sufficient?

Upvotes: 1

Views: 189

Answers (2)

Joe White
Joe White

Reputation: 97696

Usually it's best to offload the heavy lifting onto a BackgroundWorker, as Carra suggested.

But to directly answer your question, yes, you can put a Form into a separate thread. It might not be ideal in this case, because your background window would still be non-responsive a lot of the time; but it is possible.

You'd want to use a manually-created Thread (and not e.g. a Task or a ThreadPool thread), and make sure to call Thread.SetApartmentState(ApartmentState.STA) before you start the thread, since most UI requires a single-threaded apartment. Then you can create a Form inside that thread, and either call Application.Run or Form.ShowDialog.

Of course, all the usual threading restrictions apply (can only access the form and its controls from the thread that created them).

Upvotes: 0

Carra
Carra

Reputation: 17964

You should do the heavy lifting in another thread. You can use a background worker to keep things easy or manage your own threads.

Something like this:

  • Controller form presses start => Start a thread/backgroundworker and do your calculations in it
  • When the calculations are done, update your image form. You could call an event when its done and let your image/controller form subscribe to it.
  • Or when the controller form changes something before the calculations are done, you can cancel the backgroundworker and start again.

Upvotes: 2

Related Questions