条件BackgroundWorker场景

时间:2014-06-05 12:31:52

标签: c# multithreading backgroundworker

我有一个GUI,其中包含主窗体上列表框中的测试脚本列表。我希望BackgroundWorker执行不同的脚本,具体取决于从列表框中选择的项目。

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
   if(listbox.SelectedItem.ToString() == test1)
   {
      testcase test1 = new testcase(); // instantiate the script
      test1.script1(); // run the code
   }
}

但是,当我尝试这样做时,我收到InvalidOperationException occurred消息,因为我正在尝试跨线程操作。还有另一种方法可以完成这项任务吗?

2 个答案:

答案 0 :(得分:2)

您正尝试从其他线程的UI元素中读取值。 这是不允许的。因此,您获得了InvalidOperationException

UI元素由主(UI)线程拥有。

要从不同的线程访问UI元素,您需要调用当前的调度程序:

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string selectedItem = "";
    this.Dispatcher.Invoke(new Action(() => 
    {
        selectedItem = listbox.SelectedItem.ToString();
    }

    if(selectedItem == test)
    {
        testcase test1 = new testcase(); // instantiate the script
        test1.script1(); // run the code
    }
}

请注意,当您调用调度程序时,线程会同步以安全地获取交叉线程的值。您不会在调度程序中调用完整的代码,因为它不会再在不同的线程上执行

答案 1 :(得分:2)

在调用后台工作人员之前将数据传递给后台线程。

bw.RunWorkerAsync(listbox.SelectedItem.ToString());
...
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string selectedItem = (string)e.Argument;

    if(selectedItem == test)
    {
        testcase test1 = new testcase(); // instantiate the script
        test1.script1(); // run the code
    }

}