Csharp/C#教程:异步友好的DispatcherTimer包装器/子类分享


异步友好的DispatcherTimer包装器/子类

我在我的代码中运行一个DispatcherTimer ,每30秒触发一次,从服务器更新系统状态。 即使我正在调试我的服务器代码,计时器也会在客户端中触发,所以如果我已经调试了5分钟,我可能会在客户端中进行十几次超时。 最后决定我需要解决这个问题,以便制作一个更加async / await友好的DispatcherTimer。

这就是我想出的。

用法:

  var timer = new SmartDispatcherTimer(); timer.IsReentrant = false; timer.Interval = TimeSpan.FromSeconds(30); timer.TickTask = async () => { StatusMessage = "Updating..."; // MVVM property await UpdateSystemStatus(false); StatusMessage = "Updated at " + DateTime.Now; }; timer.Start(); 

这是代码。 很想听听它的任何想法

上述就是C#学习教程:异步友好的DispatcherTimer包装器/子类分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public class SmartDispatcherTimer : DispatcherTimer { public SmartDispatcherTimer() { base.Tick += SmartDispatcherTimer_Tick; } async void SmartDispatcherTimer_Tick(object sender, EventArgs e) { if (TickTask == null) { Debug.WriteLine("No task set!"); return; } if (IsRunning && !IsReentrant) { // previous task hasn't completed Debug.WriteLine("Task already running"); return; } try { // we're running it now IsRunning = true; Debug.WriteLine("Running Task"); await TickTask.Invoke(); Debug.WriteLine("Task Completed"); } catch (Exception) { Debug.WriteLine("Task Failed"); } finally { // allow it to run again IsRunning = false; } } public bool IsReentrant { get; set; } public bool IsRunning { get; private set; } public Func TickTask { get; set; } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/951377.html

(0)
上一篇 2021年11月18日
下一篇 2021年11月18日

精彩推荐