Last active
May 2, 2023 11:18
-
-
Save noseratio/dcd6ecfe9284bdc6ab6ec32344947bb4 to your computer and use it in GitHub Desktop.
A minimal console app using .NET Generic Host API
This file contains 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
// 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