Skip to content

Instantly share code, notes, and snippets.

@cphillips83
Last active January 21, 2020 04:27
Show Gist options
  • Save cphillips83/571492ab95466d01a987aca4df2f9b9a to your computer and use it in GitHub Desktop.
Save cphillips83/571492ab95466d01a987aca4df2f9b9a to your computer and use it in GitHub Desktop.
//https://github.com/marcel-dempers/docker-development-youtube-series
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace dockergraveful
{
class Program
{
static async Task Main(string[] args)
{
try
{
await new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MyService>();
})
.RunConsoleAsync();
}
catch (OperationCanceledException)
{
}
}
}
public class MyService : BackgroundService
{
protected override async Task Process(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
Console.WriteLine("Ping");
await Task.Delay(1000);
}
Console.WriteLine("Stopping");
await Task.Delay(10000);
Console.WriteLine("Stopped");
}
}
public abstract class BackgroundService : IHostedService
{
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts =
new CancellationTokenSource();
public virtual Task StartAsync(CancellationToken cancellationToken)
{
// Store the task we're executing
_executingTask = ExecuteAsync(_stoppingCts.Token);
// If the task is completed then return it,
// this will bubble cancellation and failure to the caller
if (_executingTask.IsCompleted)
{
return _executingTask;
}
// Otherwise it's running
return Task.CompletedTask;
}
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
}
try
{
// Signal cancellation to the executing method
_stoppingCts.Cancel();
}
finally
{
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite,
cancellationToken));
}
}
protected virtual async Task ExecuteAsync(CancellationToken stoppingToken)
{
//stoppingToken.Register(() =>
// _logger.LogDebug($" GracePeriod background task is stopping."));
// do
// {
await Process(stoppingToken);
await Task.Delay(5000, stoppingToken); //5 seconds delay
// }
// while (!stoppingToken.IsCancellationRequested);
}
protected abstract Task Process(CancellationToken token);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment