Skip to content

Instantly share code, notes, and snippets.

@mrchipset
Last active May 27, 2024 07:18
Show Gist options
  • Save mrchipset/a17cbda3dde3a8a4c48b638f3cd03a08 to your computer and use it in GitHub Desktop.
Save mrchipset/a17cbda3dde3a8a4c48b638f3cd03a08 to your computer and use it in GitHub Desktop.
.dot net core background console service demo
using Microsoft.Extensions.Hosting;
namespace App.HostService
{
public class AppHostService : BackgroundService
{
IHostApplicationLifetime _lifetime;
public AppHostService(IHostApplicationLifetime lifetime)
{
_lifetime = lifetime;
}
protected override async Task<object> ExecuteAsync(CancellationToken stoppingToken)
{
int loop = 0;
while (!stoppingToken.IsCancellationRequested) {
try {
Console.WriteLine("Background service working...");
await Task.Delay(5000, stoppingToken);
if (loop++ > 10) {
_lifetime.StopApplication();
}
} catch(TaskCanceledException exception)
{
Console.WriteLine($"TaskCanceledException Error: {exception.Message}");
}
}
return Task.CompletedTask;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Start Async AppHostService");
return base.StartAsync(cancellationToken);
}
public override Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Stop Async AppHostService.");
return base.StopAsync(cancellationToken);
}
}
}
using App.HostService;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
await Host.CreateDefaultBuilder()
.UseConsoleLifetime()
.ConfigureServices((context, services) => {
services.AddHostedService<AppHostService>();
})
.RunConsoleAsync();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment