C# winfrom 跨线程访问文本框

 

或者在页面加载中加入一行   TextBox.CheckForIIegalCrossThreadCalls=False;

 1 private void button1_Click(object sender,EventArgs e)
 2 {
 3     Thread thread=new Thread(ShowResult);
 4     thread.IsBackground=true;  //设置为后台线程
 5     thread.Start();
 6 }
 7 
 8 private void ShowResult()
 9 {
10      int a=0;
11      for(int i=0;i<60000000;i++)
12      {
13            a=i;
14      }
15      if(this.textBox1.InvokeRequired)//是否要对文本框进行线程访问
16      {
17            this.textBox1.Invoke(new Action<TextBox,string>(ShowTextBoxValue),this.textBox1,a.ToString());//Invoke就是去找创建textbox的线程
18      }
19       else
20      {
21           this.textBox1.Text=a.ToString();
22      }
23 }
24 private void ShowTextBoxValue(TextBox txt,string value) //通过原来的线程,主线程去执行赋值运算
25 {
26       txt.Text=value;
27 }

 

posted @ 2019-07-10 10:02  学海无涯,天道酬勤  阅读(1031)  评论(0编辑  收藏  举报