使用委托解决"线程间操作无效: 从不是创建控件“textBox1”的线程访问它" 问题

在winform编程中常遇到此类问题,造成辅助线程无法给控件赋值

 

 1 //定义委托
 2 
 3 private delegate void SetTextCallback(string text);
 4 
 5  
 6 
 7 //在给textBox1.text赋值的地方调用以下方法即可
 8 
 9 private void SetText(string text)
10         {
11             // InvokeRequired需要比较调用线程ID和创建线程ID
12             // 如果它们不相同则返回true
13             if (this.textBox1.InvokeRequired)
14             {
15                 SetTextCallback d = new SetTextCallback(SetText);
16                 this.Invoke(d, new object[] { text });
17             }
18             else
19             {
20                 this.textBox1.Text = text;
21             }
22         }

 

posted @ 2015-06-05 14:09  leechg  阅读(521)  评论(0编辑  收藏  举报