Created
October 21, 2021 19:54
-
-
Save MahdiKarimipour/c27c9e249252b5d5357ac6f03a047848 to your computer and use it in GitHub Desktop.
Base HostedService for Long Running Tasks
This file contains hidden or 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
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