首页 > 解决方案 > 跨线程操作在后台工作者 c# 中无效

问题描述

我想要一个在后台工作人员中运行的代码,但遇到了这个错误:

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

解决方案


您也应该将您的条件置于待命状态Invoke,例如

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

是有关此问题的现有线程


推荐阅读