原文发布时间为:2009-03-30 —— 来源于本人的百度文章 [由搬家工具导入]
public long str1, str2, str3, str4, str5, sum=0,sum1=0;
public void button1_Click(object sender, EventArgs e)
{
Thread.CurrentThread.Name = "主线程 ";
Thread objThreadOne = new Thread(new ThreadStart(fun1));
objThreadOne.Name = "子线程 1 ";
Thread objThreadTwo = new Thread(new ThreadStart(fun2));
objThreadTwo.Name = "子线程 2 ";
objThreadOne.Start();
objThreadTwo.Start();
objThreadOne.Priority = ThreadPriority.Highest;
}
void fun1()
{
str1 = long.Parse(textBox1.Text);
str2 = long.Parse(textBox2.Text);
lock(this)
for (long i = str1; i <= str2; i++)
{
sum = sum + i;
}
textBox4.Text = sum1.ToString();
}
void fun2()
{
str1 = long.Parse(textBox1.Text);
str2 = long.Parse(textBox2.Text);
lock (this)
for (long i = str2; i <= str1; i--)
{
sum1 = sum1 + i;
}
textBox5.Text = sum1.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
textBox4.Text = " ";
textBox1.Text = " ";
textBox2.Text = " ";
str1 = 0;
str2 = 0;
sum = 0;
}
报错线程间操作无效: 从不是创建控件“textBox4”的线程访问它。
解决方法有两种,但是推荐第二种方法:
1、System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
2、
因为你这个控件是主线程创建的,它依附于创建窗体的主线程.因此,要在子线程去访问占资源的类型,我们需要跨线程调用.textBox4.InvokeRequire用于判断是否需要跨线程,返回True为需要跨线程,此时你需要定义一个委托类来将一个含赋值语句的方法封装起来,通过textBox4.Invoke来调用这个委托.代码如下:
public delegate void SetTextHandler(string text);
private void SetText(string text)
{
if(textBox4.InvokeRequired==true)
{
SetTextHandler set=new SetTextHandler(SetText);//委托的方法参数应和SetText一致
textBox4.Invoke(set,new object[]{text}); //此方法第二参数用于传入方法,代替形参text
}
else
{
textBox4.Text=text;
}
}
那么fun2函数可以改写成:
void fun2()
{
str1 = long.Parse(textBox1.Text);
str2 = long.Parse(textBox2.Text);
lock (this)
for (long i = str2; i <= str1; i--)
{
sum1 = sum1 + i;
}
SetText( sum1.ToString());
}
注意那两句 str1 = long.Parse(textBox1.Text);也需要写成委托形式,读取数据的方法和赋值的方法类型.