title: Calling async methods from a Windows Service
body: <p>I have a Windows Service written in C# that periodically fires off background jobs. Typically, at any given time, several dozen heavily I/O bound Tasks (downloading large files, etc) are running in parallel. The service runs on a relatively busy web server (necessary for now), and I think it could benefit greatly in terms of thread conservation to use asynchronous APIs as much as possible.</p>
  
  <p>Most of this work is done. All jobs are now fully async (leveraging HttpClient, etc.), as is the main job loop (with heavy doses of Task.Delay). All that's left is to figure out how to correctly and safely fire up the main loop from the service's OnStart. Essentialy, it's the much-warned-about calling-async-from-sync dilemma. Below is what I have so far (grossly simplified).</p>
  
  <p>in Program.cs:</p>
  
  <pre><code>static void Main(string[] args) {
      TaskScheduler.UnobservedTaskException += (sender, e) =&gt; {
          // log &amp; alert!
          e.SetObserved();
      };
      ServiceBase.Run(new MyService());
  }
  </code></pre>
  
  <p>in MyService.cs:</p>
  
  <pre><code>protected override void OnStart(string[] args) {
      _scheduler.StartLoopAsync(); // fire and forget! will this get me into trouble?
  }
  </code></pre>
  
  <p>It's that call to <code>StartLoopAsync</code> that concerns me. I can't simply <code>Wait()</code> on the returned Task because OnStart needs to return relatively quickly. (Job loops need to run on a separate thread.) A couple thoughts come to mind:</p>
  
  <ul>
  <li>Am I well covered as far as unobserved exceptions by placing that handler in Main?</li>
  <li>Would there be any benefit to using Task.Run, something like <code>Task.Run(() =&gt; _scheduler.StartLoopAsync().Wait());</code> ?</li>
  <li>Would there be any benefit to calling <code>_scheduler.StartLoopAsync().ConfigureAwait(false)</code> here? (I'm doubting it since there's no <code>await</code> here.)</li>
  <li>Would there be any benefit to using <a href="http://nitoasyncex.codeplex.com/wikipage?title=AsyncContextThread">Stephen Cleary's AsyncContextThread</a> in this situation? I haven't seen any examples of using this, and since I'm starting an infinite loop I don't know that syncing back up to some context is even relevant here.</li>
  </ul>