1

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?

Srv19
  • 3,458
  • 6
  • 44
  • 75
  • Doesn't `Application.Run` block? – Phil Gan Dec 07 '12 at 12:14
  • After checking msdn it appears that yes, it does. Probably calling it from inside of another thread will do. – Srv19 Dec 07 '12 at 12:16
  • It is not a duplicate, but I think you could get a good start from this [question](http://stackoverflow.com/questions/7568376/multiple-ui-threads-winforms?rq=1) – Steve Dec 07 '12 at 12:20

2 Answers2

2

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.
Carra
  • 17,808
  • 7
  • 62
  • 75
0

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).

Community
  • 1
  • 1
Joe White
  • 94,807
  • 60
  • 220
  • 330