VB / C # .net Dynamically add background controls

I am creating a Windows Form application that dynamically creates controls based on data retrieved from a database.

I have code that runs fine in the background that loads data from a database and applies it to variables, the problem I am facing is trying to create controls using this data, I get a multi-threaded error (additional information: operation Cross-thread invalid: "flowpanelMenuRules" is controlled from a thread other than the thread in which it was created.)

I am using the BackgroundWorker_DoWork event, and the failed code is as follows:

Me.flowpanelMenuRules.Controls.Add(PanelRule(i)) 

The before code is a simple loop through a variable (which is retrieved from the database) and gathering information.

Does anyone have experience safely calling the above line? I just can't get it to work at all :(

Thanks for the help, I can send more code if necessary.

+5
source share
2 answers

My recommendation is to get BackgroundWorker to simply create controls, but not add them to the form. Instead, return the prepared controls to the caller / user interface stream through the RunWorkerCompleted event. Then add controls to your form at this point, perhaps in combination with the SuspendLayout() / ResumeLayout() methods.

+6
source

The native path for a WinForms application is to use the System.Winfows.Forms.Control methods such as Invoke() and InvokeRequired to access the user interface stream:

 if(this.flowpanelMenuRules.InvokeRequired) { this.flowpanelMenuRules.Invoke(() => AddPanelRule()); } else { AddPanelRule(); } 

You can also use the Dispatcher class.

If you are sure that you are in the user interface thread (for example, in the button.Click handler), Dispatcher.CurrentDispatcher provides a user interface thread manager, which you can later use to send from background threads to the user interface thread, as usual.

 Dispatcher.CurrentDispatcher.Invoke(() => this.flowpanelMenuRules.Controls.Add(PanelRule(i))); 
+1
source

Source: https://habr.com/ru/post/1245867/


All Articles