c# - PCL .NET 4.5 计时器

标签 c# xamarin .net-4.5 mvvmcross

我正在使用 Xamarin 和 MvvmCross 构建跨平台应用程序。我需要每分钟调用服务器进行更新(稍后我将移动到推送通知)但我无法在我的核心项目中设置计时器。我看过 MvvmCross N+42,但我相信目标项目较旧,允许计时器。下面是我的目标框架。

有没有更好的方法让我不断调用调用服务的方法?

  • .NET Framework 4.5 及更高版本
  • Windows 应用商店应用 (Windows 8) 及更高版本
  • Windows 手机 8
  • Xamarin.Android
  • Xamarin.iOS

最佳答案

@stevemorgan 的回答非常有效。 我基于该代码创建了一个 Timer 实用程序,以使其更易于重用。 我还添加了一个“runOnce”参数,它将在第一次滴答后停止计时器

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 中使用它没有任何问题:

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

关于c# - PCL .NET 4.5 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151143/

相关文章:

C# 5.0 async await 返回一个列表

c# - 为什么没有 string.Split(string) 重载?

c# - EPPlus 日期单元格数据类型不工作

c# - 存储在集合中的 IDisposable 对象是否应该手动处理?

c# - System.DllNotFoundException :/system/lib/libsqlite. 所以

.net - 使用 .Net 4.5 的功能区功能

c# - 将 DataTable 作为参数发送到存储过程

c# - 如何在 xamarin.forms 中绑定(bind)标签的 Horizo​​ntalOptions 属性

c# - Xamarin Forms - 实现单例

.net - GetGetMethod 方法和 GetMethod 属性之间的区别?