title: How to pass LongRunning flag specifically to Task.Run()?
body: <p>I need a way to set an async task as long running without using Task.Factory.StartNew(...) and instead using Task.Run(...) or something similar.</p>
  
  <p>Context:</p>
  
  <p>I have Task that loops continuously until it is externally canceled that I would like to set as 'long running' (i.e. give it a dedicated thread). This can be achieved through the code below:</p>
  
  <pre><code>var cts = new CancellationTokenSource();
  Task t = Task.Factory.StartNew(
  async () =&gt; {
  while (true)
  {
      cts.Token.ThrowIfCancellationRequested();
      try
      {
          "Running...".Dump();
          await Task.Delay(500, cts.Token);
      }
      catch (TaskCanceledException ex) { }
  } }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  </code></pre>
  
  <p>The problem is that Task.Factory.StartNew(...) does not return the active async task that is passed in but rather a 'task of running the Action' which functionally always has taskStatus of 'RanToCompletion'. Since my code needs to be able to track the task's status to see when it becomes 'Canceled' (or 'Faulted') I need to use something like below:</p>
  
  <pre><code>var cts = new CancellationTokenSource();
  Task t = Task.Run(
  async () =&gt; {
  while (true)
  {
      cts.Token.ThrowIfCancellationRequested();
      try
      {
          "Running...".Dump();
          await Task.Delay(500, cts.Token);
      }
      catch (TaskCanceledException ex) { }
  } }, cts.Token);
  </code></pre>
  
  <p>Task.Run(...), as desired, returns the async process itself allowing me to obtain actual statuses of 'Canceled' or 'Faulted'. I cannot specify the task as long running, however. So, anyone know how to best go about running an async task while both storing that active task itself (with desired taskStatus) and setting the task to long running?</p>