c# - C# DispatcherTimer 问题
问题描述
我对 WPF 计时器有疑问。
这是我的代码:
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
如您所见,时间间隔为 1 分钟。但是当我启动计时器时,1 小时后我有 10 秒的延迟。所以,我猜是我的代码处理造成了这种延迟,但我真的需要一个修复计时器,没有任何转变。
对不起你的眼睛!!
解决方案
The delay is caused by the WPF GUI thread, which runs all WPF code, like rendering and the DispatcherTimer.Tick
event. The rendering has a higher priority than a DispatcherTimer
with default priority. So when at the time your Tick
is supposed to run also some rendering is needed, the rendering gets executed first and delays your Tick by x milliseconds. This is not too bad, but unfortunately these delays can accumulate over time, if you leave the DispatcherTimer.Interval
constant. You can improve the precision of the DispatcherTimer
by shortening the DispatcherTimer.Interval
for every x milliseconds delay like this:
const int constantInterval = 100;//milliseconds
private void Timer_Tick(object? sender, EventArgs e) {
var now = DateTime.Now;
var nowMilliseconds = (int)now.TimeOfDay.TotalMilliseconds;
var timerInterval = constantInterval -
nowMilliseconds%constantInterval + 5;//5: sometimes the tick comes few millisecs early
timer.Interval = TimeSpan.FromMilliseconds(timerInterval);
For a more detail explanation see my article on CodeProject: Improving the WPF DispatcherTimer Precision
推荐阅读
- javascript - 在javascript中运行动画函数后如何添加函数/元素动作?
- .net - 如何设置 Visual Studio Pack 默认发布而不是像发布按钮这样的当前模式
- python - 如何在 Android Studio 项目中添加 Python Selenium 脚本
- spring-boot - 在 Spring Boot 的 LDAP 身份验证中使用 sAMAccountName 而不是 userPrincipalName
- java - 二元运算符 '<=' , '+=' 的错误操作数类型
- jquery - 如何在 jQuery select2 远程选择框中设置默认选择值的排序?
- php - 如何确定一行中是否有 X 个时隙?
- sql - 比较 PostgreSQL 中的两列仅显示最高值
- c# - 我无法让 OnMouseOver() 注意到我的鼠标悬停在 c# (Unity) 中的按钮上
- ios - travisci:对包进行代码签名,无法导入我的开发人员凭据之一