2016-01-06 58 views
0

我正在开发一个代码,其中必须读取数据表单列表框并上传外部文件,请按下名为Start的按钮,并使用此列表框获取错误,如下所示。在C中使用列表框线程#

“System.InvalidOperationException”类型 的未处理的异常发生在System.Windows.Forms.dll中

其他信息:跨线程操作无效:控制 “listBox1中”从其他线程访问比它创建的线程 。

我的代码是如这里在listbox.SetSelected命令如下

private void Start_Click(object sender, EventArgs e) 
{ 
Thread ss = new Thread(Automode); 
ss.Start(); 
} 

private void Automode() 
    { 
     .... 
     for (int i = 0; i < listBox1.Items.Count; i++) 
     { 
      listBox1.SetSelected(i, true); 

      string pattern = "[gxyzbcmij][-+]?[0-9]*\\.?[0-9]*"; 
      string text = listBox1.Text; 
      Regex gcode = new Regex(pattern, RegexOptions.IgnoreCase); 
      MatchCollection code = gcode.Matches(text); 
     } 
     ..... 
    } 

它给一个异常,如上所示。请提出替代方法来编写它。

+0

与往常一样,将UI代码与业务代码分开......重新设计它,以便线程代码不访问ListBox或任何其他控件。 –

回答

0

您不能从后台线程访问listBox1

如果可能,请直接在Start_Click方法中运行函数Automode()中的代码。如果您必须让代码在后台线程中运行,那么我可能会建议更类似于任务的东西,这样您仍然可以根据传递参数和等待响应来执行操作。那么你仍然可以选择listBox1项目。

1
delegate void SetSelectedCall(int index, bool option); 

private void SetSelectedElement(int index, bool option) 
{ 
    if (this.listBox1.InvokeRequired) 
    { 
    SetSelectedCall d = new SetSelectedCall(SetSelectedElement); 
    this.Invoke(d, new object[] { int index, bool option}); 
    } 
    else 
    { 
    this.listBox1.SetSelected(index,option); 
    } 
} 

摘自Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on并为此问题量身打造。

+0

这确实解决了眼前的问题,但它没有解决更深层次的设计问题。 –