views:

40

answers:

1

In my application I update a treeview in a backgrounworker thread. While updating the treeview, the combobox values are not visible. When the treeview is updated, the values appear.

Here's my backgroundworker code:

void _bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    tvCategories.Invoke((MethodInvoker)delegate()
    {
        FillCategoryTreeView(); // Fills the treeview
    }
    );
}

The code that fills my combobox:

private void FillCategoryCombo()
{
    Category categorie = new Category();
    List<Category> categories = categorie.GetQuestionCategories();

    cmbCategories.DataSource = categories;
    cmbCategories.DisplayMember = "Description";
    cmbCategories.ValueMember = "Id";
}

The combobox is filled in the constructor of the form.

The reason that I've put the treeview in a seperate thread is because the treeview must be updated. In the meantime I want to continue using the application. Therefore I need access to a combobox. But the values of the combobox are invisible while the treeview is being updated.

What to do to solve this?

+1  A: 

I'm not quite sure there is enough information in your post to fully answer the question... but assuming that you create the Background worker thread in the Constructor prior to calling the FillCategoryCombo() method... this makes sense.

In your background worker method, you immediately call Invoke which switches control right back to the UI thread, which will then be doing the work of FillCategoryTreeView() before FillCategoryCombo() has a chance to run.

If you want to asynchronously fill your treeview (assuming it comes from a long running database call), then what you need to do is actually have separate Invoke calls in FillCategoryTreeView when you specifically need to add a tree view item. That way as each database call (or whatever takes a long time) finishes, it only does an operation on the UI thread when it needs to add a physical tree node.

Nick