From 47db6d01ed9f0ef5693166aba9dd5d05f65f01e9 Mon Sep 17 00:00:00 2001 From: Sourabh Shirhatti Date: Sun, 12 May 2019 12:03:13 -0700 Subject: [PATCH] Use backgroudservice --- src/LogViewer/HostedService.cs | 46 ------------------------------- src/LogViewer/LogViewerService.cs | 2 +- 2 files changed, 1 insertion(+), 47 deletions(-) delete mode 100644 src/LogViewer/HostedService.cs diff --git a/src/LogViewer/HostedService.cs b/src/LogViewer/HostedService.cs deleted file mode 100644 index cee364d..0000000 --- a/src/LogViewer/HostedService.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Microsoft.Extensions.Hosting; -using System.Threading; -using System.Threading.Tasks; - -namespace LogViewer -{ - 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); - } -} diff --git a/src/LogViewer/LogViewerService.cs b/src/LogViewer/LogViewerService.cs index 85ec8a2..278c683 100644 --- a/src/LogViewer/LogViewerService.cs +++ b/src/LogViewer/LogViewerService.cs @@ -13,7 +13,7 @@ namespace LogViewer { - public class LogViewerService : HostedService + public class LogViewerService : BackgroundService { private readonly ILoggerFactory _loggerFactory; private readonly LogViewerServiceOptions _options;