Skip to content

Instantly share code, notes, and snippets.

@ngohungphuc
Created November 23, 2018 10:37
Show Gist options
  • Save ngohungphuc/33512903cbe40132cd05eb190dc3cac8 to your computer and use it in GitHub Desktop.
Save ngohungphuc/33512903cbe40132cd05eb190dc3cac8 to your computer and use it in GitHub Desktop.
public abstract class BackgroundService : IHostedService, IDisposable
{
private Task task;
private readonly CancellationTokenSource cancellationTokens = new CancellationTokenSource();
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
public virtual Task StartAsync(CancellationToken cancellationToken)
{
this.task = this.ExecuteAsync(this.cancellationTokens.Token);
return this.task.IsCompleted ? this.task : Task.CompletedTask;
}
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
if (this.task != null)
{
try
{
this.cancellationTokens.Cancel();
}
finally
{
await Task.WhenAny(task, Task.Delay(Timeout.Infinite, cancellationToken));
}
}
}
public virtual void Dispose()
{
this.cancellationTokens.Cancel();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment