using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EasyTemplate.Service { public interface IBackgroundService { string Status { get; } int TickCount { get; } event EventHandler? StatusChanged; } public class BackgroundTimerService : BackgroundService, IBackgroundService { private Timer? _timer; public string Status { get; private set; } = "Stopped"; public int TickCount { get; private set; } public event EventHandler? StatusChanged; protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(1)); await Task.CompletedTask; } private void DoWork(object? state) { TickCount++; Status = "Running"; StatusChanged?.Invoke(this, EventArgs.Empty); } public override async Task StopAsync(CancellationToken cancellationToken) { _timer?.Dispose(); Status = "Stopped"; StatusChanged?.Invoke(this, EventArgs.Empty); await base.StopAsync(cancellationToken); } } }