我正在使用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计时器
发布评论