BackgroundWork没有获得ComboBox的价值?

时间:2016-03-11 22:13:18

标签: c# backgroundworker

我有一个ComboBox对象,我将这些值插入到我的数据库中,它可以工作。现在我尝试创建一个BackgroundWorker来插入和控制Form的组件,例如按钮和进度以及ComboBox本身。问题是在添加BackgroundWorker之后,我无法在ComboBox中选择值,我无法理解这个问题是什么。

我怎么解决?

插入方法

/** insere Perfil + Modulo */
        private void insertPerfilModulo() {            
            Perfil perfil = (Perfil)cbxPerfilModulo.SelectedItem;
            IList<Modulo> lista = getListaModulo();

            foreach(Modulo m in lista){                
                Permissao permissao = new Permissao();
                permissao.perfil = perfil;
                permissao.modulo = m;

                Boolean exist = dao.isExistPerfilAndModulo(permissao);                
                if (exist) {
                    Permissao p = dao.getPermissao(permissao);                    
                    dao.update(p);
                }else {
                    dao.insert(permissao);
                }
            }
        }

启动BackgroundWorker的按钮

private void btnSalvarPM_Click(object sender, EventArgs e) {    
    if (!backgroundWorker1.IsBusy) {
        progressBar1.Visible = true;                
        cbxPerfilModulo.Enabled = false;
        btnSalvarPM.Enabled = false;
        backgroundWorker1.RunWorkerAsync();
    }            
}

DoWork的

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
            insertPerfilModulo();
        }

异常

The thread '<No Name>' (0x1870) has exited with code 0 (0x0).
'PubControl.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Numerics\v4.0_4.0.0.0__b77a5c561934e089\System.Numerics.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
The program '[5396] PubControl.vshost.exe: Program Trace' has exited with code 0 (0x0).
The program '[5396] PubControl.vshost.exe: Managed (v4.0.30319)' has exited with code -1 (0xffffffff).

enter image description here

1 个答案:

答案 0 :(得分:3)

您正尝试从后台工作程序访问UI线程。这是不允许的。

您需要向后台工作人员传递完成业务所需的所有信息 - 在这种情况下是组合框中的所选项目。

在这种情况下,你会有这样的事情:

  backgroundWorker1.RunWorkerAsync(cbxPerfilModulo.SelectedItem);

然后在工人中:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    Perfil perfil = (Perfil)e.Argument;
    insertPerfilModulo(perfil);
}

您需要更改方法以接受正在处理的项目的参数。