PCL .NET 4.5计时器 [英] PCL .NET 4.5 Timer

查看:105
本文介绍了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计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆