Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MahdiKarimipour/c27c9e249252b5d5357ac6f03a047848 to your computer and use it in GitHub Desktop.
Save MahdiKarimipour/c27c9e249252b5d5357ac6f03a047848 to your computer and use it in GitHub Desktop.
Base HostedService for Long Running Tasks
public abstract class MyBackgroundService : IHostedService, IDisposable
{
private Task executingTask;
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
public virtual Task StartAsync(CancellationToken cancellationToken)
{
executingTask = ExecuteAsync(cancellationTokenSource.Token);
if (executingTask.IsCompleted)
{
return executingTask;
}
return Task.CompletedTask;
}
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
if (executingTask == null)
{
return;
}
try
{
cancellationTokenSource.Cancel();
}
finally
{
await Task.WhenAny(executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
}
}
public virtual void Dispose()
{
cancellationTokenSource.Cancel();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment