Add Controls to WinForms dynamically in another Thread

I have a Winform that contains a datagridview, bindingsource, file explorer control, etc...

I need add several controls (Custom UserControls) to a Panel dynamically (like Panel.Controls.Add(...)). This process can be slow.

I want to show to the user a message (waiting).

What is the best way? I use Backgroundworker but I have problems, my application not responds and datagridview not shows scrollbar vertical, and another strange things.

Upvotes: 2

Views: 2978

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

I doubt that adding controls to a WinForm could be slow. IMHO what probably degrades the performance is fetching the data that is bound to them. So you can for example load the data in a new thread and once it is loaded, bind it to the control:

ThreadPool.QueueUserWorkItem(o =>
{
    // Simulate some expensive data fetch.
    Thread.Sleep(1000);
    string[] data = new[] { "value1", "value2" };

    if (InvokeRequired)
    {
        Action a = () => { listBox1.DataSource = data; };
        // Ensure that all UI updates are done on the main thread
        Invoke(a);
    }
});

Upvotes: 2

user62572
user62572

Reputation: 1388

A thread is probably not your best bet for gui operations like this. All controls should be created on the same thread.

Instead put a statusbar control at the bottom of your form. On the statusbar, include a progress bar and a label. When adding a control, indicate this on the statusbar by including a message in the label and incrementing the progressbar.

Upvotes: 3

Related Questions