Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class Extensions
- {
- public static IdleCancellation CancelWithIdle(this CancellationTokenSource cts, TimeSpan timeout)
- {
- return new IdleCancellation(cts, timeout);
- }
- }
- public class IdleCancellation
- {
- private readonly CancellationTokenSource _cts;
- private readonly TimeSpan _timeOut;
- private readonly Timer _timer;
- private long _lastReset;
- public IdleCancellation(CancellationTokenSource cts, TimeSpan timeOut)
- {
- _cts = cts;
- _timeOut = timeOut;
- _timer = new Timer(Callback);
- Interlocked.Exchange(ref _lastReset, DateTime.UtcNow.Ticks);
- _timer.Change(_timeOut, TimeSpan.Zero);
- _cts.Token.UnsafeRegister((_, _) =>
- {
- _timer.Dispose();
- }, null);
- }
- public void Reset()
- {
- Interlocked.Exchange(ref _lastReset, DateTime.UtcNow.Ticks);
- }
- private void Callback(object? _)
- {
- var lastReset = new DateTime(Interlocked.Read(ref _lastReset), DateTimeKind.Utc);
- var delta = DateTime.UtcNow - lastReset;
- if (delta >= _timeOut)
- {
- _timer.Dispose();
- _cts.Cancel();
- }
- else
- _timer.Change(_timeOut - delta, TimeSpan.Zero);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement