Search code examples
c#combobox

Cross-thread operation not valid in background worker c#


I want a code running in background worker but encountered this error :

'Cross-thread operation not valid: Control 'metroComboBox1' accessed from a thread other than the thread it was created on.'

private void metroRename_Click(object sender, EventArgs e)
    {
        if (backgroundWorker1.IsBusy)
            backgroundWorker1.CancelAsync();
        backgroundWorker1.RunWorkerAsync(metroComboBox1.Text);
    }

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        this.Invoke((MethodInvoker)delegate ()
        {
            string text = metroComboBox1.Text;
        });

        if (metroComboBox1.SelectedItem == "TITLE") //error here
        {
           //some code here
        }
    }

How can I use combobox inside the background worker?


Solution

  • You should place your condition under Invoke call as well, e.g.

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        this.Invoke((MethodInvoker)delegate()
        {
            string text = metroComboBox1.Text;
            if (metroComboBox1.SelectedItem == "TITLE") 
            {
               //some code here
            }
        });        
    }
    

    Here is an existing thread about this problem