日期:2014-05-18  浏览次数:20984 次

线程与控件如何交互?
声明了一个线程:
private Thread CTrlThread;

声明了一个方法:
private void CTrlThr()
{
  this.listBox1.Items.Add("AAAAA");
}

在按钮事件中启动线程:
private void button4_Click(object sender, EventArgs e)
{
  CTrlThread = new Thread(new System.Threading.ThreadStart(CTrlThr));
  this.CTrlThread.Start();
}

运行到黑体字部分,报错:“Control.Invoke 必须用于与在独立线程上创建的控件交互。”
估计应为窗体中的listBox1是一个线程,我创建的CTrlThread线程不能与其交互。
但是我记得以前写过个类似的,是用线程控制窗体上label显示不同数字的。现在忘了!
请问谁知道怎么处理这种问题!??谢谢

------解决方案--------------------
贴错了是这个
 System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
------解决方案--------------------
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

如果使用频率不高 可以用上面的 ,太高回失去响应(死锁)····


C# code

  delegate void AddTextToControl_delegate(string str);
void Begin()
{
 Thread addColorThread = new Thread(new ThreadStart(AddColorToList_M));
        addColorThread.Start();
}
 void AddTextToRichTextBox(string text)
        {
            if (rTextBox.InvokeRequired)
            {
                AddTextToControl_delegate d = new AddTextToControl_delegate(AddTextToRichTextBox);
                rTextBox.Invoke(d, new object[] { text});
            }
            else
            {
                rTextBox.AppendText(text + "\n");
                rTextBox.Select(rTextBox.TextLength, 0);
                rTextBox.ScrollToCaret();
            }
        }

调用 AddTextToRichTextBox(string str)给控件赋值

------解决方案--------------------
声明了一个线程: 
private Thread CTrlThread; 

声明一个委托:
Delegate void DelegateCTrlThr();
声明了一个方法: 
private void CTrlThr() 

this.listBox1.Items.Add("AAAAA"); 


封装方法:
DelegateCTrlTr objDelegateCTrlTr = new DelegateCTrlTr (CTrlThr);
用INVOKE方法 调用委托:
private void ThreadMethod()
{
 this.INVOKE(objDelegateCTrlTr );
}
private void 

在按钮事件中启动线程 注意线程封装的方法是用ThreadMethod()方法: 
private void button4_Click(object sender, EventArgs e) 

CTrlThread = new Thread(new System.Threading.ThreadStart(ThreadMethod)); 
this.CTrlThread.Start(); 
}