title: Asp.Net core long running/background task
body: <p>Is the following a correct pattern to implement long running background work in Asp.Net Core? Or should I be using some form of <code>Task.Run</code>/<code>TaskFactory.StartNew</code> with <code>TaskCreationOptions.LongRunning</code> option?</p>
  
  <pre><code>    public void Configure(IApplicationLifetime lifetime)
      {
          lifetime.ApplicationStarted.Register(() =&gt;
          {
              // not awaiting the 'promise task' here
              var t = DoWorkAsync(lifetime.ApplicationStopping);
  
              lifetime.ApplicationStopped.Register(() =&gt;
              {
                  try
                  {
                      // give extra time to complete before shutting down
                      t.Wait(TimeSpan.FromSeconds(10));
                  }
                  catch (Exception)
                  {
                      // ignore
                  }
              });
          });
      }
  
      async Task DoWorkAsync(CancellationToken token)
      {
          while (!token.IsCancellationRequested)
          {
              await // async method
          }
      }
  </code></pre>