“一直找解决方案”这本身就不严谨。你的所谓多线程程序,是按照“仅仅影响单个TextBox”的值而创建线程吗?比如说你的一个异步访问服务器进行查询的操作,它可能影响100个TextBox、Label等等控件,你是用100个线程进行一次服务器查询?还是用一个线程?如果用一个线程进行查询,那么你就应该只调用一次Invoke方法(实际上我从来不用Invoke,我只用BeginInvoke)。而不是什么“几十个、几百个”。而你“为了多线程而多线程”,把每一个简单的值都弄一个线程而且阻塞输出,你用多线程这肯定比不用多线程还慢至少十倍速度啦。
InvokeHelper:多线程修改主界面控件属性并调用其中方法
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
<span style="color: #FF0000;"> this.textBox1.Invoke</span>(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
请看后面的最新代码部分
{
textBox1.Text = "测试..";
}));
如果有另外一个控件
CrossThreadCalls.SafeInvoke(this.textBox2, new CrossThreadCalls.TaskDelegate(delegate()
{
textBox2.Text = "测试..";
}));
一个控件对应一个CrossThreadCalls.SafeInvoke即可
如果你用begin-end Invoke的方法对,你根本就不需要就负责线程的分配,你只需要注意你的代码逻辑的控制
线程多了并不好