Skip to content

Instantly share code, notes, and snippets.

@nantcom
Created April 25, 2021 11:17
Show Gist options
  • Save nantcom/3b1dbfed672c510ad136c6ce6f8c9a8c to your computer and use it in GitHub Desktop.
Save nantcom/3b1dbfed672c510ad136c6ce6f8c9a8c to your computer and use it in GitHub Desktop.
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