BackgroundService.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using Microsoft.Extensions.Hosting;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace EasyTemplate.Service
  8. {
  9. public interface IBackgroundService
  10. {
  11. string Status { get; }
  12. int TickCount { get; }
  13. event EventHandler? StatusChanged;
  14. }
  15. public class BackgroundTimerService : BackgroundService, IBackgroundService
  16. {
  17. private Timer? _timer;
  18. public string Status { get; private set; } = "Stopped";
  19. public int TickCount { get; private set; }
  20. public event EventHandler? StatusChanged;
  21. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  22. {
  23. _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
  24. await Task.CompletedTask;
  25. }
  26. private void DoWork(object? state)
  27. {
  28. TickCount++;
  29. Status = "Running";
  30. StatusChanged?.Invoke(this, EventArgs.Empty);
  31. }
  32. public override async Task StopAsync(CancellationToken cancellationToken)
  33. {
  34. _timer?.Dispose();
  35. Status = "Stopped";
  36. StatusChanged?.Invoke(this, EventArgs.Empty);
  37. await base.StopAsync(cancellationToken);
  38. }
  39. }
  40. }