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

4 篇文章 0 订阅
1 篇文章 0 订阅
很好的一篇文章,讲得很透彻: 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";
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值