Skip to content

Instantly share code, notes, and snippets.

@noseratio
Last active May 2, 2023 11:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noseratio/dcd6ecfe9284bdc6ab6ec32344947bb4 to your computer and use it in GitHub Desktop.
Save noseratio/dcd6ecfe9284bdc6ab6ec32344947bb4 to your computer and use it in GitHub Desktop.
A minimal console app using .NET Generic Host API
// https://twitter.com/noseratio/status/1535173151910350848
// https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using var host = Host.CreateDefaultBuilder(Environment.GetCommandLineArgs())
.ConfigureLogging(
logging =>
{
logging.ClearProviders();
//logging.AddConsole();
})
.ConfigureServices((context, services) =>
// add any other services
services.AddHostedService<AsyncRunner>())
.Build();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await host.RunAsync(cts.Token);
class AsyncRunner : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IHostApplicationLifetime _lifeTime;
public AsyncRunner(IServiceProvider serviceProvider, IHostApplicationLifetime lifeTime)
{
// request any serices via constructor parameters or via serviceProvider
_serviceProvider = serviceProvider;
_lifeTime = lifeTime;
}
protected virtual async Task MainAsync(CancellationToken stoppingToken)
{
// run until cancelled
while (true)
{
Console.WriteLine($"Hello at {DateTime.Now}");
await Task.Delay(TimeSpan.FromSeconds(0.5), stoppingToken);
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await MainAsync(stoppingToken);
}
catch (OperationCanceledException)
{
}
finally
{
_lifeTime.StopApplication();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment