wp下使用Timer 还是DispatcherTimer?

DispatcherTimer属于UI线程,Timer非UI线程,运行在后台。

 DispatcherTimer里面执行等待动作或者时间过长,可能会导致UI假死。

但是 Timer的 TimerCallback 委托指定希望 Timer 执行的方法。 计时器委托在构造计时器时指定,并且不能更改。

所以用什么要随情况而定。

下面是实现代码:

public partial class MainPage : PhoneApplicationPage
     {
         DispatcherTimer Dtimer;
         Timer timer;
     
         // 构造函数
         public MainPage()
         {
             InitializeComponent();
     
             Dtimer = new DispatcherTimer();
             Dtimer.Interval = TimeSpan.FromSeconds(1);
             Dtimer.Tick+=new EventHandler(timer_Tick);
             Dtimer.Start();
     
     
             timer= new Timer(CallBalk,text,1000,1000);
         }
     
    
         void timer_Tick(object sender,EventArgs e)
         {
             Debug.WriteLine(DateTime.Now.ToShortTimeString());
             Debug.WriteLine("DispatcherTimer");
         }
         void CallBalk(object  state)
         {
             //Dispatcher.BeginInvoke();
             Debug.WriteLine("Timer");
         }
     }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
System.Timers.TimerDispatcherTimer都是用于定时执行任务的计时器类,但它们在使用方式和适用场景上有所不同。 System.Timers.Timer是一个多线程计时器,适用于在后台线程执行周期性任务。它是基于底层的System.Threading.Timer实现的,可以在指定的时间间隔内重复执行任务。以下是一个使用System.Timers.Timer的示例: ```csharp static System.Timers.Timer Timer1 = new System.Timers.Timer(); static void Main() { Timer1.Interval = 1000; // 设置时间间隔为1秒 Timer1.Elapsed += new ElapsedEventHandler(PeriodicTaskHandler); // 绑定事件处理程序 Timer1.Start(); // 启动计时器 } static void PeriodicTaskHandler(object sender, ElapsedEventArgs e) { // 执行周期性任务的代码 } ``` DispatcherTimer是一个UI线程计时器,适用于在UI线程上执行周期性任务。它是基于WPF的Dispatcher对象实现的,可以在指定的时间间隔内重复执行任务,并且可以直接更新UI元素。以下是一个使用DispatcherTimer的示例: ```csharp private void StartTimer() { DispatcherTimer dispatcherTimer = new DispatcherTimer(); dispatcherTimer.Tick += OnTimerHandler; // 绑定事件处理程序 dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100); // 设置时间间隔为100毫秒 dispatcherTimer.Start(); // 启动计时器 } private void OnTimerHandler(object sender, EventArgs e) { string strTime = DateTime.Now.ToString("HH:mm:ss:fff"); // 获取当前时间 lbTime.Content = strTime; // 更新UI元素 } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值