C#跨线程访问控件

方法一:

1  public Form1()
2         {
3             //程序启动加入这行:
4             Control.CheckForIllegalCrossThreadCalls = false;
5          }       

 

方法二:使用委托实现

 

 1 public delegate void DelSetTextBoxText(TextBox txtBox, string txt);
 2         public void SetTextBoxText(TextBox txtBox, string txt)
 3         {
 4             try
 5             {
 6                 if (txtBox.InvokeRequired)
 7                 {
 8                     DelSetTextBoxText del = new DelSetTextBoxText(SetTextBoxText);
 9                     this.Invoke(del, new object[] { txtBox, txt });
10                 }
11                 else
12                 {
13                     txtBox.Text = “Hello World”;
14                 }
15             }
16             catch (Exception ex)
17             {
18             }
19         }

 

 

 

方法三:使用委托和Lambda

1  this.textBox1.Invoke((MethodInvoker)(() => 
2     {
3         this.textBox1.Text ="Hello World!" 
4     }));

 

posted @ 2018-02-28 16:05  BaoMingZhu  阅读(186)  评论(0编辑  收藏  举报