PCL .NET 4.5 Minuterie

Je construis des applications multiplateformes avec Xamarin et MvvmCross. Je dois appeler le serveur pour les mises à jour toutes les minutes (je passerai plus tard aux notifications push) mais je ne parviens pas à créer de timer dans mon projet principal. J’ai vu MvvmCross N + 42, mais je crois que les projets cibles sont plus anciens, ce qui permet la timer. Ci-dessous, le cadre de ma cible.

Existe-t-il un meilleur moyen pour moi d’appeler constamment une méthode qui appelle un service?

  • .NET Framework 4.5 et supérieur
  • Applications Windows Store (Windows 8) et supérieures
  • Windows Phone 8
  • Xamarin.Android
  • Xamarin.iOS

@stevemorgan answer fonctionne vraiment bien. J’ai créé un utilitaire Timer basé sur ce code pour le rendre plus réutilisable. J’ai également ajouté un paramètre “runOnce” qui arrêtera le chronomètre après le premier 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(); } } } } } 

J’utilise ceci dans MvvmCross sans problèmes:

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

Vous pouvez toujours le faire vous-même grâce aux merveilles de async / wait:

 public async Task RunTimer() { while(_timerRunning) { // Do Work // ... await Task.Delay(_timerInterval); } } 

Lorsque vous l’appelez, n’attendez pas . Il fonctionnera sur un thread d’arrière-plan et vous pouvez terminer la boucle en définissant le champ _timerRunning ailleurs (ou en supprimant la tâche renvoyée par l’appel).