ill mg
ill mg

Reputation: 351

C# Can I create Controls in another thread?

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

Upvotes: 6

Views: 2986

Answers (3)

ulatekh
ulatekh

Reputation: 1490

Controls, no. Forms, yes.

Thread thread = new Thread( () =>
   {
         var yourForm = new YourForm();
         Application.Run(yourForm);
   });
thread.ApartmentState = ApartmentState.STA;
thread.Start();

Upvotes: 0

user166390
user166390

Reputation:

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.

Upvotes: 7

Nacimota
Nacimota

Reputation: 23225

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.

Upvotes: 3

Related Questions