-
-
Save jrgcubano/df881511445f029f4c0cc2537eaa2fe9 to your computer and use it in GitHub Desktop.
Simple PCL C# Timer class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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