【问题标题】:Cross-thread operation not valid in background worker c#跨线程操作在后台工作者 c# 中无效
【发布时间】:2019-03-18 12:52:36
【问题描述】:

我想在后台运行代码,但遇到了这个错误:

'跨线程操作无效:控件'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
        }
    }

如何在后台工作人员中使用组合框?

【问题讨论】:

    标签: c# combobox


    【解决方案1】:

    你也应该把你的条件放在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 是一个关于这个问题的现有线程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 2020-08-08
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 2011-07-11
      相关资源
      最近更新 更多