Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. using Microsoft.Extensions.Hosting;
  2. using System;
  3. using System.ServiceProcess;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Backup.Service
  8. {
  9. public class ServiceLifeTime : ServiceBase, IHostLifetime
  10. {
  11. public ServiceLifeTime(IApplicationLifetime applicationLifeTime)
  12. {
  13. ApplicationLifeTime = applicationLifeTime ?? throw new ArgumentNullException(nameof(applicationLifeTime));
  14. DelayStart = new TaskCompletionSource<object>();
  15. }
  16.  
  17. public IApplicationLifetime ApplicationLifeTime { get; }
  18. public TaskCompletionSource<object> DelayStart { get; set; }
  19.  
  20. public Task StopAsync(CancellationToken cancellationToken)
  21. {
  22. Stop();
  23. return Task.CompletedTask;
  24. }
  25.  
  26. protected override void OnStart(string[] args)
  27. {
  28. DelayStart.TrySetResult(null);
  29. base.OnStart(args);
  30. }
  31.  
  32. protected override void OnStop()
  33. {
  34. ApplicationLifeTime.StopApplication();
  35. base.OnStop();
  36. }
  37.  
  38. public Task WaitForStartAsync(CancellationToken cancellationToken)
  39. {
  40. cancellationToken.Register(() => DelayStart.TrySetCanceled());
  41. ApplicationLifeTime.ApplicationStopping.Register(Stop);
  42. new Thread(Run).Start();
  43. return DelayStart.Task;
  44. }
  45.  
  46. private void Run()
  47. {
  48. try
  49. {
  50. Run(this);
  51. DelayStart.TrySetException(new InvalidOperationException("Stopped, without starting the service"));
  52. }
  53. catch (Exception ex)
  54. {
  55. DelayStart.TrySetException(ex);
  56. }
  57. }
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement