invoke方法操作ui线程的控件属性

列一个简单例子来说明。

WinForm:

这里必须利用delegate委托的invoke

 1         private void button1_Click(object sender, EventArgs e)
 2         {
 3             Thread th1 = new Thread(new ThreadStart(dod));
 4             th1.Start();
 5         }
 6 
 7         private delegate void myinvoke(int s);
 8 
 9         private void dod()
10         {
11             myinvoke mi = new myinvoke(dowork);
12             mi.Invoke(2000);
13         }
14 
15         private void dowork(int s)
16         {
17             int i = 0;
18             while (true)
19             {
20                 textBox1.Text = i.ToString();
21                 i++;
22                 Thread.Sleep(s);
23             }
24         }
25 
26         private void Form1_Load(object sender, EventArgs e)
27         {
28             Control.CheckForIllegalCrossThreadCalls = false;
29         }

WPF:

这里主要是Dispatcher.Invoke()的用法

 1         private void button1_Click(object sender, RoutedEventArgs e)
 2         {
 3             Thread th1 = new Thread(new ThreadStart(DoWork));
 4             th1.Start();
 5         }
 6         
 7         private void DoWork()
 8         {
 9             int i = 0;
10             while (true)
11             {
12                 Dispatcher.Invoke(new Action(() =>
13                 {
14                     textBox1.Text = i.ToString(); 
15                     progressBar1.Value ++;
16                 }), System.Windows.Threading.DispatcherPriority.Background);
17                 i++;
18                 Thread.Sleep(500);
19             }
20         }

 

posted @ 2013-02-17 09:17  一个坟头  阅读(695)  评论(0编辑  收藏  举报