Created
November 23, 2018 10:37
-
-
Save ngohungphuc/33512903cbe40132cd05eb190dc3cac8 to your computer and use it in GitHub Desktop.
This file contains 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 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