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

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

总结一下,跨 线程 更新 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;
      }));
}


2) DispatcherTimer

// 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();

3)BackgroundWorker

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";
    }
}


你可能感兴趣的:(WPF跨线程更新UI的3种方法)