Created
January 15, 2018 08:27
-
-
Save xuanye/61cfe05bbf01a5c3055a95372fdd0193 to your computer and use it in GitHub Desktop.
实现IHostedService 用于实现后台服务,类似while(true)的基类
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 HostedService : IHostedService | |
{ | |
private Task _executingTask; | |
private CancellationTokenSource _cts; | |
public Task StartAsync(CancellationToken cancellationToken) | |
{ | |
// Create a linked token so we can trigger cancellation outside of this token's cancellation | |
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); | |
// Store the task we're executing | |
_executingTask = ExecuteAsync(_cts.Token); | |
// If the task is completed then return it, otherwise it's running | |
return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask; | |
} | |
public async Task StopAsync(CancellationToken cancellationToken) | |
{ | |
// Stop called without start | |
if (_executingTask == null) | |
{ | |
return; | |
} | |
// Signal cancellation to the executing method | |
_cts.Cancel(); | |
// Wait until the task completes or the stop token triggers | |
await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken)); | |
// Throw if cancellation triggered | |
cancellationToken.ThrowIfCancellationRequested(); | |
} | |
// Derived classes should override this and execute a long running method until | |
// cancellation is requested | |
protected abstract Task ExecuteAsync(CancellationToken cancellationToken); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment