The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HostedService.cs 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using Microsoft.Extensions.Hosting;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace Teknik.Utilities
  8. {
  9. public abstract class HostedService : IHostedService
  10. {
  11. private Task _executingTask;
  12. private CancellationTokenSource _cts;
  13. public Task StartAsync(CancellationToken cancellationToken)
  14. {
  15. // Create a linked token so we can trigger cancellation outside of this token's cancellation
  16. _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  17. // Store the task we're executing
  18. _executingTask = ExecuteAsync(_cts.Token);
  19. // If the task is completed then return it, otherwise it's running
  20. return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
  21. }
  22. public async Task StopAsync(CancellationToken cancellationToken)
  23. {
  24. // Stop called without start
  25. if (_executingTask == null)
  26. {
  27. return;
  28. }
  29. // Signal cancellation to the executing method
  30. _cts.Cancel();
  31. // Wait until the task completes or the stop token triggers
  32. await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken));
  33. // Throw if cancellation triggered
  34. cancellationToken.ThrowIfCancellationRequested();
  35. }
  36. // Derived classes should override this and execute a long running method until
  37. // cancellation is requested
  38. protected abstract Task ExecuteAsync(CancellationToken cancellationToken);
  39. }
  40. }