Skip to content

Instantly share code, notes, and snippets.

@fugaku
Last active March 31, 2020 20:41
Show Gist options
  • Select an option

  • Save fugaku/df72b04f9c3d6a883690ea157348d4ee to your computer and use it in GitHub Desktop.

Select an option

Save fugaku/df72b04f9c3d6a883690ea157348d4ee to your computer and use it in GitHub Desktop.
BackgroundService for long running
public abstract class BackgroundService : IHostedService, IDisposable
{
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
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));
}
}
public virtual void Dispose()
{
_stoppingCts.Cancel();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment