Advertisement
Guest User

Untitled

a guest
Mar 31st, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. public static class Extensions
  2. {
  3. public static IdleCancellation CancelWithIdle(this CancellationTokenSource cts, TimeSpan timeout)
  4. {
  5. return new IdleCancellation(cts, timeout);
  6. }
  7. }
  8.  
  9. public class IdleCancellation
  10. {
  11. private readonly CancellationTokenSource _cts;
  12. private readonly TimeSpan _timeOut;
  13. private readonly Timer _timer;
  14.  
  15. private long _lastReset;
  16.  
  17. public IdleCancellation(CancellationTokenSource cts, TimeSpan timeOut)
  18. {
  19. _cts = cts;
  20. _timeOut = timeOut;
  21.  
  22. _timer = new Timer(Callback);
  23. Interlocked.Exchange(ref _lastReset, DateTime.UtcNow.Ticks);
  24. _timer.Change(_timeOut, TimeSpan.Zero);
  25.  
  26. _cts.Token.UnsafeRegister((_, _) =>
  27. {
  28. _timer.Dispose();
  29. }, null);
  30. }
  31.  
  32. public void Reset()
  33. {
  34. Interlocked.Exchange(ref _lastReset, DateTime.UtcNow.Ticks);
  35. }
  36.  
  37. private void Callback(object? _)
  38. {
  39. var lastReset = new DateTime(Interlocked.Read(ref _lastReset), DateTimeKind.Utc);
  40.  
  41. var delta = DateTime.UtcNow - lastReset;
  42. if (delta >= _timeOut)
  43. {
  44. _timer.Dispose();
  45. _cts.Cancel();
  46. }
  47. else
  48. _timer.Change(_timeOut - delta, TimeSpan.Zero);
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement