N Chary
N Chary

Reputation: 1

Cross thread operation on WinForm controls

Here is my code scenario,

In main thread I create panel(s) (based on some configuration), and then in the next step based on the file type (like video, ppt, image...) I create appropriate controls (dynamically) to show on the forms.

The creation of the control will be done in separate threads (for each file). After creating the control, it throws an error when I try to add that control to the panel (which was created in the main thread), something like cross thread violation, control was accessed from one thread other that it was created.

Can some one please help me in this regard?

In this scenario, everything - creating the panels and controls - will be dynamic. Nothing will be static.

I tried some of the articles found here on StackOverflow (like, control.BeginInvoke() .. etc), but wasn't able to solve my problem.

Upvotes: 0

Views: 836

Answers (2)

Andreas Paulsson
Andreas Paulsson

Reputation: 7813

Controls should only be created and accessed from the main GUI thread.

You can do work in other threads, but do not access GUI components from other threads.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 942267

You cannot create controls in another thread and add them to a form that was created in the main UI thread. Windows requires that the child windows owned by a top-level window belong to the same thread. You have to create them in the UI thread. Leverage the Control.Begin/Invoke() method.

Upvotes: 4

Related Questions