Skip to content

Instantly share code, notes, and snippets.

@YARG
Created February 25, 2015 08:37
Show Gist options
  • Save YARG/681f426b78af6d77baab to your computer and use it in GitHub Desktop.
Save YARG/681f426b78af6d77baab 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(); }
}
}
@johnslaby
Copy link

Thanks, this ws exactly what I was looking for

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment