Dispatcher中Invoke与BeginInvoke

本文探讨了WPF中Dispatcher的Invoke和BeginInvoke方法。尽管两者都会阻塞UI线程,但Invoke是同步的,会等待回调执行完成,而BeginInvoke则是异步的,调用后立即返回,后续任务按线程优先级执行。通过示例和测试,展示了它们在实际应用中的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文: Dispatcher中Invoke与BeginInvoke

[同步]Invoke

Application.Current.Dispatcher.Invoke(AutoIncreaseNumber);

[异步]BeginInvoke

Application.Current.Dispatcher.BeginInvoke((Action)AutoIncreaseNumber);

两者都会阻塞UI线程

基于WPF4.5.1示例

Invoke 按钮对应的是InvokeCommand

BeginInvoke按钮对应的是BeginInvokeCommand

可以发现,在执行按钮的命令时,UI线程是会阻塞,计时器并不会走动

  1 public class MainViewModel : ViewModelBase
  2     {
  3         public MainViewModel()
  4         {
  5             DispatcherTimer timer = new DispatcherTimer();
  6             timer.Interval = TimeSpan.FromSeconds(1);
  7             timer.Tick += timer_Tick;
  8             timer.Start();
  9         }
 10 
 11         void timer_Tick(object sender, EventArgs e)
 12         {
 13             Now = DateTime.Now;
 14         }
 15 
 16         private DateTime now = DateTime.Now;
 17 
 18         public DateTime Now
 19         {
 20             get { return now; }
 21             set
 22             {
 23                 now = value;
 24                 RaisePropertyChanged("Now");
 25             }
 26         }
 27 
 28 
 29 
 30         private int number;
 31         /// <summary>
 32         /// 数值用于显示
 33         /// </summary>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值