跨线程操作在后台工作程序C#中无效

时间:2019-03-18 12:52:36

标签: c# combobox cross-thread

我想要在后台工作程序中运行的代码,但遇到此错误:

  

“跨线程操作无效:控制'metroComboBox1'从其创建线程以外的线程访问。”

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
        }
    }

如何在后台工作程序中使用组合框?

1 个答案:

答案 0 :(得分:0)

您也应将条件放在Invoke下,例如

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

Here是关于此问题的现有主题