Advertisement
ivandrofly

PeriodicTimer: .NET 6

Mar 11th, 2023 (edited)
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.27 KB | None | 0 0
  1. namespace PeriodicTimerDemo;
  2.  
  3. // REF
  4. // https://www.youtube.com/watch?v=J4JL4zR_l-0
  5.  
  6. public class BackgroundTask
  7. {
  8.     private readonly PeriodicTimer _periodicTimer;
  9.     private Task _task;
  10.    
  11.     // TaskCompletionSource : learn more in SingletonSean
  12.     // private CancellationToken _cancellationToken = new();
  13.     private readonly CancellationTokenSource _cancellationTokenSource = new();
  14.  
  15.     public BackgroundTask(TimeSpan timeSpan)
  16.     {
  17.         _periodicTimer = new PeriodicTimer(timeSpan);
  18.     }
  19.  
  20.     public void Start() => _task = WorkAsync();
  21.  
  22.     private async Task WorkAsync()
  23.     {
  24.         try
  25.         {
  26.             while (await _periodicTimer.WaitForNextTickAsync(_cancellationTokenSource.Token))
  27.             {
  28.                 // Console.WriteLine("Ta-da!");
  29.                 Console.WriteLine(DateTime.Now.ToString("O"));
  30.             }
  31.         }
  32.         catch (OperationCanceledException exception)
  33.         {
  34.             // user cancel using StopAsync which uses CancellationTokenSource
  35.         }
  36.     }
  37.  
  38.     public async Task StopAsync()
  39.     {
  40.         if (_task is null)
  41.         {
  42.             return;
  43.         }
  44.        
  45.         _cancellationTokenSource.Cancel();
  46.         await _task;
  47.         _cancellationTokenSource.Dispose();
  48.     }
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement