net core ihostedservice code example

Example: .net core custom IHostedService

public abstract class CoordinatedBackgroundService : IHostedService, IDisposable
{
    private readonly CancellationTokenSource appStoppingTokenSource = new CancellationTokenSource();

    protected readonly IHostApplicationLifetime appLifetime;

    public CoordinatedBackgroundService(IHostApplicationLifetime appLifetime)
    {
        this.appLifetime = appLifetime;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine($"IHostedService.StartAsync for {GetType().Name}");
        appLifetime.ApplicationStarted.Register(
            async () => 
            await ExecuteAsync(appStoppingTokenSource.Token).ConfigureAwait(false)
        );
        return InitializingAsync(cancellationToken);
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine($"IHostedService.StopAsync for {GetType().Name}");
        appStoppingTokenSource.Cancel();
        await StoppingAsync(cancellationToken).ConfigureAwait(false);
        Dispose();
    }

    protected virtual Task InitializingAsync(CancellationToken cancelInitToken)
        => Task.CompletedTask;

    protected abstract Task ExecuteAsync(CancellationToken appStoppingToken);

    protected virtual Task StoppingAsync(CancellationToken cancelStopToken)
        => Task.CompletedTask;

    public virtual void Dispose()
    { }
}