Windows Service running Async code not waiting on work to complete

后端 未结 1 514
难免孤独
难免孤独 2021-02-08 13:06

In Brief

I have a Windows Service that executes several jobs as async Tasks in parallel. However, when the OnStop is called, it seems that these are a

相关标签:
1条回答
  • 2021-02-08 13:40

    Your problem is that OnStop is async void. So, when it does await this.AllJobsCompleted, what actually happens is that it returns from OnStop, which the SCM interprets as having stopped, and terminates the process.

    This is one of the rare scenarios where you'd need to block on a task, because you cannot allow OnStop to return until after the task completes.

    This should do it:

    protected override void OnStop()
    {
      this.RequestAdditionalTime(100000); // some large number        
      _cancelSource.Cancel();     
      TraceMessage("Task cancellation requested."); // Last thing traced
    
      try
      {
        bool allStopped = this.AllJobsCompleted.GetAwaiter().GetResult();          
        TraceMessage(string.Format("allStopped = '{0}'.", allStopped));
      }
      catch (Exception e)
      {
        TraceMessage(e.Message);
      }
    }
    
    0 讨论(0)
提交回复
热议问题