winform 实现多线程更新UI控件的方法

 1  2 Control.CheckForIllegalCrossThreadCalls = false;//关闭安全检查,为了安全一般不采用此代码
 3 =============================================================================================================================
 4 
 5  6 一般多线程代码:不能实现跨线程数据交互:
 7 Thread thread = new Thread(new ThreadStart(Test));
 8 thread.IsBackground = true;            
 9 thread.Start();
10 
11 ===============================================================================================================================
12 13 通过UI控件的Invoke/BeginInvoke方法更新,实现后台线程和UI线程数据交换
14 
15 1.定义一个委托
16 delegate void delegate1(string text);     //设置这个委托支持异步调用文本框控件的文本属性。不同控件可能需要不同参数
17 
18 2.定义控件更新方法SetText                  //这个是实现线程数据交换的关键
19 private void SetText(string text)                                                         
20         {
21 
22             if (this.textBox1.InvokeRequired)            //如果调用控件的线程和创建创建控件的线程不是同一个则为True
23             {
24                 while (!this.textBox1.IsHandleCreated)
25                 {
26                     //解决窗体关闭时出现“访问已释放句柄“的异常
27                     if (this.textBox1.Disposing || this.textBox1.IsDisposed)
28                         return;
29                 }
30                 delegate1 d = new delegate1(SetText);  //委托实例化
31                 this.textBox1.Invoke(d, new object[] { text });
32             }
33             else
34             {
35                 this.textBox1.Text = text;
36             }
37         }
38 
39 3.次线程运行的主要代码
40 private void test()
41         {
42             int i;
43             for (i = 1; i <= 10; i++)
44             {
45                 Thread.Sleep(1000);
46                 this.SetText(i.ToString());          //此处需要和UI线程实时交换数据,我们引用上门定义的方法SetText来实现,这一步是关键   
47             }
48             MessageBox.Show("运行完毕");
49 
50         }
51 4.控件事件代码
52 private void button1_Click(object sender, EventArgs e)
53         {
54             Thread thread = new Thread(new ThreadStart(test));  //创建新线程
55             thread.IsBackground = true;                         //设定线程为后台线程
56             thread.Start();                                     //启动新线程
57 
58         }

猜你喜欢

转载自www.cnblogs.com/gougouwang/p/12741648.html