将计时器添加到Xamarin应用程序(c#)

所以我需要一个计时器从60秒倒计时。 我是Xamarin的新手,不知道它接受了什么。 有关如何开始的任何建议?

它将用于android

你可以使用System.Timers.Timer吗?

您可以使用System.Threading.Timer类,该类在Xamarin文档中有记录: https : //developer.xamarin.com/api/type/System.Threading.Timer/

或者,对于Xamarin.Forms,您可以通过Device类访问跨平台的Timer:

 Device.StartTimer(TimeSpan.FromSeconds(1), () => { // called every 1 second // do stuff here return true; // return true to repeat counting, false to stop timer }); 

如果你只需要Android就可以使用

 System.Threading.Timer 

在使用Xamarin Forms的共享代码中,您可以使用

 Device.StartTimer(...) 

或者您可以使用以下高级function实现一个yourselfe:

 public sealed class Timer : CancellationTokenSource { private readonly Action _callback; private int _millisecondsDueTime; private readonly int _millisecondsPeriod; public Timer(Action callback, int millisecondsDueTime) { _callback = callback; _millisecondsDueTime = millisecondsDueTime; _millisecondsPeriod = -1; Start(); } public Timer(Action callback, int millisecondsDueTime, int millisecondsPeriod) { _callback = callback; _millisecondsDueTime = millisecondsDueTime; _millisecondsPeriod = millisecondsPeriod; Start(); } private void Start() { Task.Run(() => { if (_millisecondsDueTime <= 0) { _millisecondsDueTime = 1; } Task.Delay(_millisecondsDueTime, Token).Wait(); while (!IsCancellationRequested) { //TODO handle Errors - Actually the Callback should handle the Error but if not we could do it for the callback here _callback(); if(_millisecondsPeriod <= 0) break; if (_millisecondsPeriod > 0 && !IsCancellationRequested) { Task.Delay(_millisecondsPeriod, Token).Wait(); } } }); } public void Stop() { Cancel(); } protected override void Dispose(bool disposing) { if (disposing) { Cancel(); } base.Dispose(disposing); } } 

你可以随时使用

 Task.Factory.StartNewTaskContinuously(YourMethod, new CancellationToken(), TimeSpan.FromMinutes(10)); 

请务必将以下类添加到项目中

 static class Extensions { ///  /// Start a new task that will run continuously for a given amount of time. ///  /// Provides access to factory methods for creating System.Threading.Tasks.Task and System.Threading.Tasks.Task`1 instances. /// The action delegate to execute asynchronously. /// The System.Threading.Tasks.TaskFactory.CancellationToken that will be assigned to the new task. /// The interval between invocations of the callback. /// The started System.Threading.Tasks.Task. public static Task StartNewTaskContinuously(this TaskFactory taskFactory, Action action, CancellationToken cancellationToken, TimeSpan timeSpan , string taskName = "") { return taskFactory.StartNew(async () => { if (!string.IsNullOrEmpty(taskName)) { Debug.WriteLine("Started task " + taskName); } while (!cancellationToken.IsCancellationRequested) { action(); try { await Task.Delay(timeSpan, cancellationToken); } catch (Exception e) { break; } } if (!string.IsNullOrEmpty(taskName)) { Debug.WriteLine("Finished task " + taskName); } }); } } 

是的,您可以使用System.Timers.Timer

在Android中,我们可以像这样使用java.util.Timer :

  private int i; final Timer timer=new Timer(); TimerTask task=new TimerTask() { @Override public void run() { if (i < 60) { i++; } else { timer.cancel(); } Log.e("time=",i+""); } }; timer.schedule(task, 0,1000); 

在Xamarin.Android中我们也可以像这样使用java.util.Timer :

 [Activity(Label = "Tim", MainLauncher = true)] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); Timer timer = new Timer(); timer.Schedule(new MyTask(timer),0,1000); } } class MyTask : TimerTask { Timer mTimer; public MyTask(Timer timer) { this.mTimer = timer; } int i; public override void Run() { if (i < 60) { i++; } else { mTimer.Cancel(); } Android.Util.Log.Error("time",i+""); } }