0

Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

I having problems trying to get things to work with a BackgroundWorker.

I have a checkbox which when click I want to call the BackgroundWorkers RunWorkerAsync method:

    private void checkBoxLoadRecords_CheckedChanged(object sender, EventArgs e)
    {
        bw.RunWorkerAsync();
    }

So within the DoWork event I call the SelectionChangeComitted event on one of my combos:

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        comboSelectedIDs_SelectionChangeCommitted(sender, e);
    }

Within the SelectionChangeComitted method I receive an error on the first line where I try to retrieve the ID into a variable. The error I receive is: Cross-thread operation not valid: Control 'comboSelectedIDs' accessed from a thread other than the thread it was created on.

void comboSelectedIDs_SelectionChangeCommitted(object sender, EventArgs e)
{
    int idToUse = (int)multiSelectedIDs.SelectedValue; //Errors here!
    SetupNamesCombo(idToUse);
}

How do I get round this problem?

I think I'm going to have a similar problem when using my custom controls as they use the combos text value and I would like to get that in the BackgroundWorker.

I'm using C# 4.0

Thanks in advance.

Community
  • 1
  • 1
Sun
  • 4,458
  • 14
  • 66
  • 108

2 Answers2

0

Use the Dispatcher class to access to the UI elements from different threads:

        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            int idToUse = (int)multiSelectedIDs.SelectedValue;
        });

Or if you are in a code behind file you can just do this without the Deployment.Current.

laszlokiss88
  • 4,001
  • 3
  • 20
  • 26
0

You cannot access UI controls in any thread other than the UI thread.

One solution is to save the values of the UI controls in a separate POCO object, so you can access them from the background worker.

Maarten
  • 22,527
  • 3
  • 47
  • 68