DispatchTimer - prevent蜱事件被触发,如果previous滴答仍在运行 [英] DispatchTimer - Prevent the tick event to be triggered if the previous tick is still running

查看:162
本文介绍了DispatchTimer - prevent蜱事件被触发,如果previous滴答仍在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Silverlight应用程序,我有code,有运行每500毫秒块。我计划Ø使用DispatcherTimer实现这一目标(见下文code)。

In a Silverlight app, I have a block of code that has to run every 500ms. I am planning o use a DispatcherTimer to achieve this (see code below).

DispatcherTimer dt = new DispatcherTimer();
dt.Interval = new TimeSpan(0, 0, 0, 0, 500); // 500 Milliseconds
dt.Tick += new EventHandler(dt_Tick);
dt.Start();

然而,可能发生的code块花费的时间超过500毫秒执行(的code块做了一些Web服务调用)。怎样确保,如果一个电话是目前正在进行的DispatcherTimer不会触发另一个事件?什么是选择,什么是最好的方法是什么?使用锁?

However, it may happen that the block of code takes longer than 500ms to execute (the block of code does some webservice calls). How do I make sure that if a call is currently in progress, the DispatcherTimer doesn't trigger another event? What are the options and what is the best way? Using locks?

推荐答案

DispatcherTimer 只有的运行调度线程上 - 所以没有办法你可以有在同一时间运行两个处理器。这是可能的,他们会排队,直接层出不穷运行过程中的一个, - 你应该检查

The DispatcherTimer only runs on the dispatcher thread - so there's no way you could have two handlers running at the same time. It's possible they'll be queued up and run one directly after another, of course - you should check.

不过,您的不应该的是让在 DispatcherTimer 反正Web服务调用。做一个后台线程,否则你阻塞UI更新所有你在等待Web服务的时间。基本上你不应该做的UI线程任何长时间运行的工作。使用其他各种定时器中的一个(如 System.Timers.Timer的 )定期在一个线程池线程执行工作,并利用调度回叫,当你有一些数据需要显示在UI线程用户界面。

However, you shouldn't be making a web service call in a DispatcherTimer anyway. Do it in a background thread, otherwise you're blocking the UI for updating all the time that you're waiting for the web service. Basically you shouldn't do any long-running work in the UI thread. Use one of the various other timers (e.g. System.Timers.Timer) to regularly perform work on a thread pool thread and use the dispatcher to call back to the UI thread when you've got some data which needs to be displayed on the UI.

当然,现在你已经得到了新的计时器射击多次兼任的潜在问题,在多个线程。一个选项,以避免这是对自动复位属性设置为false,只是安排下一个计时器周期在当前的结束。

Of course, now you've got the potential problem of the new kind of timer firing multiple times concurrently, on multiple threads. One option to avoid this is to set the AutoReset property to false, and just schedule the next timer tick at the end of the current one.

这篇关于DispatchTimer - prevent蜱事件被触发,如果previous滴答仍在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆