Last active
May 27, 2024 07:18
-
-
Save mrchipset/a17cbda3dde3a8a4c48b638f3cd03a08 to your computer and use it in GitHub Desktop.
.dot net core background console service demo
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
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); | |
} | |
} | |
} |
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
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