title: ASP.NET Core: Kestrel web server and background Task hosted on single console process
body: <p>Is this a bad idea to use same console app instance as Kestrel web server self-host and host process for some background work?</p>
  
  <pre><code>public class Program
      {
          private static IServiceRoot _root;
  
          public static async Task Main(string[] args)
          {
              _root = new HostContainer().Resolve&lt;IServiceRoot&gt;();
  
              // Starting some background work
              Task.Run(async () =&gt;
              {
                  while (true)
                  {
                      await Task.Delay(1000).ConfigureAwait(false);
                      await _root.PerformWorkAsync().ConfigureAwait(false);
                  }
              }).DoNotAwait();
  
              // Starting web server
              BuildWebHost(args).Run();
          }
  
  
          public static IWebHost BuildWebHost(string[] args) =&gt;
              WebHost.CreateDefaultBuilder(args)
                  .UseStartup&lt;Startup&gt;()
                  .ConfigureServices(services =&gt;
                  {
                      services.AddSingleton&lt;IServiceRoot&gt;(_root);
                  }).Build();
      }
  </code></pre>
  
  <p><strong>UPDATE:</strong>
  Background work is a heavy CPU/IO bound task that should run continiously (gets data from Web, stores in DB), I just use ASP.NET Core as Web API to control it's status over HTTP. Looks like the tail wags the dog in this case. Is there more preferable approaches here? (I use Azure). Should I move IHostedService I've implemented to WebJob?</p>