Created
September 9, 2020 06:48
-
-
Save rstropek/f48d767980def4fbb4bd16b5af7a514b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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