5

Normally controls are created at the main thread. Is it possible to create some of the child controls in another thread?

ill mg
  • 331
  • 4
  • 8

3 Answers3

7

tl,dr Don't do it.

The controls can be created on a different thread, however, when they are added to the parent (created on a different thread), then there will likely be a cross-thread exception raised. I am not sure if this exception is "guaranteed", but don't do it. (There are cross-thread exceptions instead of implicit marshaling for a reason; better to die fast than deadlock later.)

Cross-threading and [winform] controls don't mix. Of course, if different forms are on different threads, and each form's children are on the same thread as the form, and cross-thread access is guarded or used via "invoke" or similar ... but a form isn't a "child" control.

Happy coding.


Sample cross-thread exception message:

System.InvalidOperationException: Cross-thread operation not valid: Control '...' accessed from a thread other than the thread it was created on.

3

I'm not sure why you would want to do this. What I would do is call back to a method on the main thread using a delegate and add the controls there.

Nacimota
  • 22,395
  • 6
  • 42
  • 44
0

Controls, no. Forms, yes.

Thread thread = new Thread( () =>
   {
         var yourForm = new YourForm();
         Application.Run(yourForm);
   });
thread.ApartmentState = ApartmentState.STA;
thread.Start();
ulatekh
  • 1,311
  • 1
  • 14
  • 19