Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jrgcubano/df881511445f029f4c0cc2537eaa2fe9 to your computer and use it in GitHub Desktop.
Save jrgcubano/df881511445f029f4c0cc2537eaa2fe9 to your computer and use it in GitHub Desktop.
Simple PCL C# Timer class
using System;
using System.Threading;
using System.Threading.Tasks;
namespace YARG.Core.Utils
{
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;
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