停止子系统:单个CancellationToken与Stop方法

时间:2018-10-04 09:17:05

标签: .net architecture .net-core task-parallel-library

我有一个简单的.net核心控制台应用程序,其中包含多个长期运行的后台服务。服务在应用程序启动时启动。我想根据用户要求正确停止它们。 Microsoft提供了用于实现长期运行的基础类-['Fruit_3', 'Fruit_1']

BackgroundService

public abstract class BackgroundService : IHostedService, IDisposable { private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource(); private Task _executingTask; /// <summary> /// This method is called when the <see cref="T:Microsoft.Extensions.Hosting.IHostedService" /> starts. The implementation should return a task that represents /// the lifetime of the long running operation(s) being performed. /// </summary> /// <param name="stoppingToken">Triggered when <see cref="M:Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)" /> is called.</param> /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the long running operations.</returns> protected abstract Task ExecuteAsync(CancellationToken stoppingToken); /// <summary> /// Triggered when the application host is ready to start the service. /// </summary> /// <param name="cancellationToken">Indicates that the start process has been aborted.</param> public virtual Task StartAsync(CancellationToken cancellationToken) { this._executingTask = this.ExecuteAsync(this._stoppingCts.Token); if (this._executingTask.IsCompleted) return this._executingTask; return Task.CompletedTask; } /// <summary> /// Triggered when the application host is performing a graceful shutdown. /// </summary> /// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param> public virtual async Task StopAsync(CancellationToken cancellationToken) { if (this._executingTask == null) return; try { this._stoppingCts.Cancel(); } finally { Task task = await Task.WhenAny(this._executingTask, Task.Delay(-1, cancellationToken)); } } public virtual void Dispose() { this._stoppingCts.Cancel(); } 允许通过调用方法BackgroundService停止服务。 同样,我们可以使用单一方法和取消令牌通过这种方式来实现长期运行的服务:

StopAsync

两种方法都能解决我的问题。但是我无法确定在代码组织和匹配类语义方法方面哪个更好。您会选择哪种方法,为什么?

0 个答案:

没有答案