简体   繁体   English

Xamarin PCL缺少System.Timer

[英]System.Timer missing from Xamarin PCL

I am building a Xamarin cross platform app targeting IOS Android and Windows Phone 8.1 using .Net 4.5.1. 我正在使用.Net 4.5.1构建一个针对IOS Android和Windows Phone 8.1的Xamarin跨平台应用程序。 When I try to reference System.Timers in the PCL project, it is not there. 当我尝试在PCL项目中引用System.Timers时,它不存在。 How do I fix this? 我该如何解决?

You can use : Device.StartTimer 您可以使用:Device.StartTimer

Syntax : 句法 :

public static void StartTimer (TimeSpan interval, Func<bool> callback)

Examples : increment number every 1 seconds for 1 minutes 示例:每1秒递增1分钟

int number = 0;
Device.StartTimer(TimeSpan.FromSeconds(1),() => {
    number++;
    if(number <= 60) 
    {
        return true; //continue
    }
    return false ; //not continue

});

Examples : wait for 5 seconds to run function one time 示例:等待5秒钟以运行一次功能

Device.StartTimer(TimeSpan.FromSeconds(5),() => {
    DoSomething();
    return false ; //not continue
});

I noticed this the other day. 前几天我注意到了这一点。 Eventhough the class is in the API documentation System.Threading.Timer Class ..Annoying. 虽然这个类是在API文档System.Threading.Timer Class ..Annoying。

Anyway I created my own Timer class, using Task.Delay() : 无论如何,我使用Task.Delay()创建了自己的Timer类:

public class Timer
{

        private int _waitTime;
        public int WaitTime
        {
            get { return _waitTime; }
            set { _waitTime = value; }
        }

        private bool _isRunning;
        public bool IsRunning
        {
            get { return _isRunning; }
            set { _isRunning = value; }
        }

        public event EventHandler Elapsed;
        protected virtual void OnTimerElapsed()
        {
            if (Elapsed != null)
            {
                Elapsed(this, new EventArgs());
            }
        }

        public Timer(int waitTime)
        {
            WaitTime = waitTime;
        }

        public async Task Start()
        {
            int seconds = 0;
            IsRunning = true;
            while (IsRunning)
            {
                if (seconds != 0 && seconds % WaitTime == 0)
                {
                    OnTimerElapsed();
                }
                await Task.Delay(1000);
                seconds++;
            }
        }

        public void Stop()
        {
            IsRunning = false;
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM