timer计时 wpf_ay wpf SmartDispatcherTimer异步处理计时器

本文介绍了SmartDispatcherTimer,一个在WPF中用于异步处理的计时器类。它在计时器触发时检查是否可以执行任务,防止重入并确保任务的正确执行。示例代码展示了如何设置和使用该计时器来更新系统状态。
摘要由CSDN通过智能技术生成

异步处理计时器

使用方法如下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();

库的代码如下: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; }

}

推荐您阅读更多有关于“WPF4.5,”的文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值