title: How to stop and resume worker service?
body: <p>Within a WPF application I have configured a hosted service to perform specific activity in background (Followed <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&amp;tabs=visual-studio" rel="nofollow noreferrer">this article</a>). 
  This is how hosted service is configured in App.xaml.cs.</p>
  
  <pre><code>public App()
          {
              var environmentName = Environment.GetEnvironmentVariable("HEALTHBOOSTER_ENVIRONMENT") ?? "Development";
              IConfigurationRoot configuration = SetupConfiguration(environmentName);
              ConfigureLogger(configuration);
              _host = Host.CreateDefaultBuilder()
                  .UseSerilog()
                  .ConfigureServices((hostContext, services) =&gt;
                  {
                      services.AddHostedService&lt;Worker&gt;()
                      .AddOptions()
                      .AddSingleton&lt;IMailSender, MailSender&gt;()
                      .AddSingleton&lt;ITimeTracker, TimeTracker&gt;()
                      .AddSingleton&lt;NotificationViewModel, NotificationViewModel&gt;()
                      .AddTransient&lt;NotificationWindow, NotificationWindow&gt;()
                      .Configure&lt;AppSettings&gt;(configuration.GetSection("AppSettings"));
                  }).Build();
  
              AssemblyLoadContext.Default.Unloading += Default_Unloading;
  
              Console.CancelKeyPress += Console_CancelKeyPress;
  
              SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
          }
  </code></pre>
  
  <p>And started on startup</p>
  
  <pre><code>/// &lt;summary&gt;
      /// Handles statup event
      /// &lt;/summary&gt;
      /// &lt;param name="e"&gt;&lt;/param&gt;
      protected override async void OnStartup(StartupEventArgs e)
      {
          try
          {
              Log.Debug("Starting the application");
              await _host.StartAsync(_cancellationTokenSource.Token);
              base.OnStartup(e);
          }
          catch (Exception ex)
          {
              Log.Error(ex, "Failed to start application");
              await StopAsync();
          }
      }
  </code></pre>
  
  <p>Now I want to stop the hosted service when the system goes to sleep and restart the service when the system resumes. I tried this</p>
  
  <pre><code>/// &lt;summary&gt;
      /// Handles system suspend and resume events
      /// &lt;/summary&gt;
      /// &lt;param name="sender"&gt;&lt;/param&gt;
      /// &lt;param name="e"&gt;&lt;/param&gt;
      private async void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
      {
          switch (e.Mode)
          {
              case PowerModes.Resume:
                  Log.Warning("System is resuming. Restarting the host");
                  try
                  {
                      _cancellationTokenSource = new CancellationTokenSource();
                      await _host.StartAsync(_cancellationTokenSource.Token);
                  }
                  catch (Exception ex)
                  {
                      Log.Error(ex, $"{ex.Message}");
                  }
                  break;
  
              case PowerModes.Suspend:
                  Log.Warning("System is suspending. Canceling the activity");
                  _cancellationTokenSource.Cancel();
                  await _host.StopAsync(_cancellationTokenSource.Token);
                  break;
          }
      }
  </code></pre>
  
  <p>Stopping the host is working fine But when the host is restarted, I am getting '<code>System.OperationCanceledException</code>'. As per my understanding hosted service lifetime is independent of application lifetime. Is my understanding wrong? </p>
  
  <p>This question- <a href="https://stackoverflow.com/questions/51469881/asp-net-core-ihostedservice-manual-start-stop-pause/51470811">ASP.NET Core IHostedService manual start/stop/pause(?)</a> is similar but the answer is to pause and restart the service based on configuration which seems like a hack so I am looking for a standard way.</p>
  
  <p>Any thoughts?</p>