WPF跨线程更新UI的3种方法
很好的一篇文章,讲得很透彻:WPF Threads: Build More Responsive Apps With The Dispatcher
总结一下,跨线程更新UI的3种方法:
1)Dispatcher
复制代码2) DispatcherTimer
复制代码3)BackgroundWorker
复制代码
总结一下,跨线程更新UI的3种方法:
1)Dispatcher
- void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
- {
- this.Dispatcher.Invoke(DispatcherPriority.Normal, new System.Windows.Forms.MethodInvoker(delegate()
- {
- this.ProgressBar.Value = e.ProgressPercentage;
- }));
- }
- // Create a Timer with a Normal Priority
- _timer = new DispatcherTimer();
- // Set the Interval to 2 seconds
- _timer.Interval = TimeSpan.FromMilliseconds(2000);
- // Set the callback to just show the time ticking away
- // NOTE: We are using a control so this has to run on
- // the UI thread
- _timer.Tick += new EventHandler(delegate(object s, EventArgs a)
- {
- statusText.Text = string.Format(
- "Timer Ticked: {0}ms", Environment.TickCount);
- });
- // Start the timer
- _timer.Start();
- BackgroundWorker _backgroundWorker = new BackgroundWorker();
- ...
- // Set up the Background Worker Events
- _backgroundWorker.DoWork += _backgroundWorker_DoWork;
- backgroundWorker.RunWorkerCompleted +=
- _backgroundWorker_RunWorkerCompleted;
- // Run the Background Worker
- _backgroundWorker.RunWorkerAsync(5000);
- ...
- // Worker Method
- void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
- {
- // Do something
- }
- // Completed Method
- void _backgroundWorker_RunWorkerCompleted(
- object sender,
- RunWorkerCompletedEventArgs e)
- {
- if (e.Cancelled)
- {
- statusText.Text = "Cancelled";
- }
- else if (e.Error != null)
- {
- statusText.Text = "Exception Thrown";
- }
- else
- {
- statusText.Text = "Completed";
- }
- }
浙公网安备 33010602011771号