Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace PeriodicTimerDemo;
- // REF
- // https://www.youtube.com/watch?v=J4JL4zR_l-0
- public class BackgroundTask
- {
- private readonly PeriodicTimer _periodicTimer;
- private Task _task;
- // TaskCompletionSource : learn more in SingletonSean
- // private CancellationToken _cancellationToken = new();
- private readonly CancellationTokenSource _cancellationTokenSource = new();
- public BackgroundTask(TimeSpan timeSpan)
- {
- _periodicTimer = new PeriodicTimer(timeSpan);
- }
- public void Start() => _task = WorkAsync();
- private async Task WorkAsync()
- {
- try
- {
- while (await _periodicTimer.WaitForNextTickAsync(_cancellationTokenSource.Token))
- {
- // Console.WriteLine("Ta-da!");
- Console.WriteLine(DateTime.Now.ToString("O"));
- }
- }
- catch (OperationCanceledException exception)
- {
- // user cancel using StopAsync which uses CancellationTokenSource
- }
- }
- public async Task StopAsync()
- {
- if (_task is null)
- {
- return;
- }
- _cancellationTokenSource.Cancel();
- await _task;
- _cancellationTokenSource.Dispose();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement