PCL .NET 4.5计时器

编程入门 行业动态 更新时间:2024-10-10 19:21:43
本文介绍了PCL .NET 4.5计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Xamarin和MvvmCross构建跨平台应用程序.我需要每分钟调用服务器一次更新(我将稍后移动以推送通知),但是我无法在Core Project中设置计时器.我见过MvvmCross N + 42,但我相信目标项目较旧,可以使用计时器.下面是我的目标框架.

I am building cross platform apps with Xamarin and MvvmCross. I need to call the server to the updates every minute (I will move to push notifications later) but I am unable to make a timer in my Core Project. I've seen MvvmCross N+42 but I believe the target projects are older which allows the timer. Below is my target framework.

我是否有更好的方法来不断调用可调用服务的方法?

Is there a better way for me to constantly call a method which calls a service?

  • .NET Framework 4.5及更高版本
  • Windows应用商店应用(Windows 8)及更高版本
  • Windows Phone 8
  • Xamarin.Android
  • Xamarin.iOS
推荐答案

@stevemorgan答案非常有效. 我基于该代码创建了一个Timer实用程序,以使其更可重用. 我还添加了一个"runOnce"参数,该参数将在第一次滴答之后停止计时器

@stevemorgan answer works really well. I created a Timer utility based on that code to make it more reusable. I also added a "runOnce" parameter that will stop the timer after the first tick

public class PclTimer { public bool IsRunning { get; private set; } public TimeSpan Interval { get; set; } public Action Tick { get; set; } public bool RunOnce { get; set; } public Action Stopped { get; set; } public Action Started { get; set; } public PclTimer(TimeSpan interval, Action tick = null, bool runOnce = false) { Interval = interval; Tick = tick; RunOnce = runOnce; } public PclTimer Start() { if (!IsRunning) { IsRunning = true; Started?.Invoke(); var t = RunTimer(); } return this; } public void Stop() { IsRunning = false; Stopped?.Invoke(); } private async Task RunTimer() { while (IsRunning) { await Task.Delay(Interval); if (IsRunning) { Tick?.Invoke(); if (RunOnce) { Stop(); } } } } }

我正在MvvmCross中使用它,没有问题:

I´m using this in MvvmCross with no issues:

timer = new Timer(TimeSpan.FromSeconds(4), () => ShowViewModel<UserMatchViewModel>(), true) .Start();

更多推荐

PCL .NET 4.5计时器

本文发布于:2023-11-06 08:43:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563214.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   PCL   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!