Skip to content

Instantly share code, notes, and snippets.

@rstropek
Created September 9, 2020 06:48
Show Gist options
  • Save rstropek/f48d767980def4fbb4bd16b5af7a514b to your computer and use it in GitHub Desktop.
Save rstropek/f48d767980def4fbb4bd16b5af7a514b to your computer and use it in GitHub Desktop.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
var host = new HostBuilder()
.ConfigureServices((hostContext, services) => services.AddHostedService<ShutdownService>())
.UseConsoleLifetime()
.Build();
await host.RunAsync();
class ShutdownService : IHostedService
{
private bool pleaseStop;
private Task BackgroundTask;
private readonly IHostApplicationLifetime applicationLifetime;
public ShutdownService(IHostApplicationLifetime applicationLifetime)
{
this.applicationLifetime = applicationLifetime;
}
public Task StartAsync(CancellationToken _)
{
Console.WriteLine("Starting service");
BackgroundTask = Task.Run(async () =>
{
while (!pleaseStop)
{
await Task.Delay(50);
}
Console.WriteLine("Background task gracefully stopped");
});
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Stopping service");
pleaseStop = true;
await BackgroundTask;
Console.WriteLine("Service stopped");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment