WPF跨线程更新UI的3种方法

很好的一篇文章,讲得很透彻:WPF Threads: Build More Responsive Apps With The Dispatcher

总结一下,跨线程更新UI的3种方法:

1)Dispatcher
  1. void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  2. {
  3.       this.Dispatcher.Invoke(DispatcherPriority.Normal, new System.Windows.Forms.MethodInvoker(delegate()
  4.       {
  5.           this.ProgressBar.Value = e.ProgressPercentage;
  6.       }));
  7. }
复制代码
2) DispatcherTimer
  1. // Create a Timer with a Normal Priority

  2. _timer = new DispatcherTimer();



  3. // Set the Interval to 2 seconds

  4. _timer.Interval = TimeSpan.FromMilliseconds(2000);



  5. // Set the callback to just show the time ticking away

  6. // NOTE: We are using a control so this has to run on

  7. // the UI thread

  8. _timer.Tick += new EventHandler(delegate(object s, EventArgs a)

  9. {

  10.     statusText.Text = string.Format(

  11.         "Timer Ticked:  {0}ms", Environment.TickCount);

  12. });



  13. // Start the timer

  14. _timer.Start();
复制代码
3)BackgroundWorker
  1. BackgroundWorker _backgroundWorker = new BackgroundWorker();

  2. ...

  3. // Set up the Background Worker Events

  4. _backgroundWorker.DoWork += _backgroundWorker_DoWork;

  5. backgroundWorker.RunWorkerCompleted +=

  6.     _backgroundWorker_RunWorkerCompleted;



  7. // Run the Background Worker

  8. _backgroundWorker.RunWorkerAsync(5000);



  9. ...



  10. // Worker Method

  11. void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)

  12. {

  13.     // Do something

  14. }



  15. // Completed Method

  16. void _backgroundWorker_RunWorkerCompleted(

  17.     object sender,

  18.     RunWorkerCompletedEventArgs e)

  19. {

  20.     if (e.Cancelled)

  21.     {

  22.         statusText.Text = "Cancelled";

  23.     }

  24.     else if (e.Error != null)

  25.     {

  26.         statusText.Text = "Exception Thrown";

  27.     }

  28.     else

  29.     {

  30.         statusText.Text = "Completed";

  31.     }

  32. }
复制代码
posted @ 2011-10-25 15:49  therockthe  阅读(689)  评论(0)    收藏  举报