Missing System.Timer in Xamarin PCL

I am building an Xamarin cross platform application focused on IOS Android and Windows Phone 8.1 using .Net 4.5.1. When I try to reference System.Timers in a PCL project, it is not there. How to fix it?

+6
source share
2 answers

You can use: Device.StartTimer

Syntax:

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

Examples: increment number every 1 second for 1 minute

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

Examples: wait 5 seconds to run the function once

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

I noticed this the other day. Despite the fact that the class is in the API documentation for System.Threading.Timer Class ..Annoying.

In any case, I created my own Timer class using Task.Delay() :

 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; } } 
+5
source

Source: https://habr.com/ru/post/989911/


All Articles