Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RXBlog - CSharp Timer Sample (Sample for RoslynPad)
public class TimeStopWhenNoOneCares
{
private long _Time;
private CancellationTokenSource _Canceller;
private Action<long> _TimeHasSpassed;
public event Action<long> TimeHasSpassed
{
add {
_TimeHasSpassed += value;
if (_Canceller == null)
{
_Canceller = new CancellationTokenSource();
this.RunTimeInterval( _Canceller.Token );
}
}
remove {
_TimeHasSpassed -= value;
if (_TimeHasSpassed == null)
{
_Canceller.Cancel();
}
}
}
private void RunTimeInterval(CancellationToken token)
{
Task.Run( ()=>{
while (token.IsCancellationRequested == false)
{
_TimeHasSpassed?.Invoke(_Time);
Task.Delay(1000).Wait();
_Time++;
}
_Canceller?.Dispose();
_Canceller = null;
});
}
}
TimeStopWhenNoOneCares t = new();
Action<long> processTime = (time)=>{
Console.WriteLine( time );
};
t.TimeHasSpassed += processTime;
Console.ReadLine();
t.TimeHasSpassed -= processTime;
Console.WriteLine( "Time stop" );
Console.ReadLine();
Console.WriteLine( "Time continue from last value" );
t.TimeHasSpassed += processTime;
Console.ReadLine();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment