Created
February 25, 2015 08:37
-
-
Save YARG/681f426b78af6d77baab to your computer and use it in GitHub Desktop.
Simple PCL C# Timer class
This file contains 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
Thanks, this ws exactly what I was looking for