Skip to content

Instantly share code, notes, and snippets.

@RedTahr
Created January 6, 2016 19:59
Show Gist options
  • Save RedTahr/1dd7a5da06c2b04e7fa2 to your computer and use it in GitHub Desktop.
Save RedTahr/1dd7a5da06c2b04e7fa2 to your computer and use it in GitHub Desktop.
My copy of Montemagnos FrenchPressTimer (for those times when I want a System.Timer in Xamarin.Forms PCL)
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ....Core.Control {
// https://github.com/jamesmontemagno/FrenchPressTimer/blob/master/SimpleTimerPortable/Timer.cs
internal delegate void TimerCallback(object state);
internal sealed class Timer : CancellationTokenSource, IDisposable {
public Timer(TimerCallback callback, object state, int dueTime, int period) {
Task.Delay(dueTime, Token).ContinueWith(async (t, s) => {
var tuple = (Tuple<TimerCallback, object>)s;
while(true) {
if(IsCancellationRequested)
break;
await Task.Run(() => tuple.Item1(tuple.Item2));
await Task.Delay(period);
}
}, Tuple.Create(callback, state), CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.Default);
}
public new void Dispose() { base.Cancel(); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment