Syed
Syed

Reputation: 931

Cross thread violation while adding UserControl from worker thread to Main UI thread in Winform

I have an application which tab page based. To decrease the startup time I am creating only the tab page which is shown to the user.

After launching the Form, I used BackgroundWorker to create other tab pages. Tab pages contains usercontrols with databinding.

It is working fine. The issue is: With one tab page I am getting cross thread violation. That tab page having databinding also.

So what will be problem in this scenario?

Thanks is advance.

Upvotes: 1

Views: 214

Answers (1)

Phil Wright
Phil Wright

Reputation: 22936

WinForms controls have thread affinity. The means they should be accessed on the same thead they are created on. This is because WinForms is actually just a wrapper around Win32 functionality and the code that manages your windows and child controls in Win32 is not thread safe. Hence your Form and child controls should only be accessed on the same thread they are created.

In your case you should not be creating TabPage instances using a BackgroundWorker thread or indeed any other thread than the main thread which is the location I assume you have the main Form that contains the TabControl you are adding the pages into.

Often developers get lucky and manage to use controls in different threads to which they were created and it does not crash. But this is just pure luck and sooner or later it will start failing.

Upvotes: 3

Related Questions