How to handle async Start() errors in TopShelf
<p>I have a TopShelf service that uses async code to connect to web services and other application servers.</p>

<p>If it's unable to initialize its connections on startup, the service should log some errors and gracefully stop.</p>

<p>I've had a look at <a href="https://stackoverflow.com/questions/23791696/how-to-catch-exception-and-stop-topshelf-service">this question</a> about stopping TopShelf when the start conditions aren't met. <a href="https://stackoverflow.com/a/28239617/531971">This answer</a> talks about using the TopShelf HostControl to stop the service.</p>

<p>However, that answer relies on the <code>ServiceConfigurator&lt;T&gt;.WhenStarted&lt;T&gt;(Func&lt;T, HostControl, bool&gt; start)</code> method.</p>

<p>I am currently configuring the TopShelf service in the standard way:</p>

<pre><code>x.Service&lt;MyService&gt;(s =&gt;
{
    s.ConstructUsing(() =&gt; new MyService());
    s.WhenStarted(s =&gt; s.Start());
    s.WhenStopped(s =&gt; s.Stop());
});
</code></pre>

<p>However my service's <code>Start()</code> method is actually <code>async</code>, defined like this:</p>

<pre><code>public async void Start()
{
    await Init();
    while (!_canceller.Token.IsCancellationRequested)
    {
        await Poll();
    }
}
</code></pre>

<p>This seems to work fine. But I use the await keyword in several places in the function. So, I can't simply change my <code>Start()</code> method to take a <code>HostControl</code> and return a <code>bool</code>, because I would have to return <code>Task&lt;bool&gt;</code> from an <code>async</code> method.</p>

<p>I'm currently allowing exceptions to bubble up from the Start() function so that TopShelf can see them and automatically stop the service when the exception bubbles up. However, the exceptions are then totally unhandled by my code, and I therefore end up with nasty unhandled exception error messages in the various logs I write to. Which I would prefer to replace with a nice error message and a clean service shut-down.</p>

<p>So, I have two questions:</p>

<ol>
<li>Is there any problem with using an <code>async void Start()</code> method for TopShelf?</li>
<li>Is there a way to make it so that if <code>Init()</code> throws an exception, the exception details are gracefully logged and then the service stops, given that my service runs <code>async</code> code?</li>
</ol>