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

查看:23
本文介绍了PCL .NET 4.5 计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Xamarin 和 MvvmCross 构建跨平台应用程序.我需要每分钟调用服务器进行更新(稍后我将转向推送通知),但我无法在我的核心项目中设置计时器.我见过 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天全站免登陆