2014-06-05 29 views
0

我有一个GUI,其中包含主窗体上的列表框中的测试脚本列表。我希望BackgroundWorker根据从列表框中选择的项目执行不同的脚本。有条件的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

在调用您的后台工作程序之前将数据传递给后台线程。

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 
    } 

}

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

注意,当你调用调度,同步线程安全地获得价值跨线程。您不希望在调度程序中调用完整的代码,因为它不会在不同的线程上执行

+0

我只能得到'this.Invoke' – Nevets

+1

@nevets你在WPF或的WinForms?两者的语法略有不同。这个概念是一样的 – middelpat