title: How to force Task.Factory.StartNew to a background thread?
body: <p>I have seen numerous other questions similar to this but did not find my answer there.</p>
  
  <p>My problem was that I was creating threads with the following flow:</p>
  
  <pre><code>private void btn_Click(object sender, EventArgs e)
  {
      service.GetCount(
          (count, ex) =&gt;
          {
              if (ex != null)
                  return;
  
              for (int i = 0; i &lt; count; i++)
              {
                  service.Get(onItemReceived, i);
              }
          }
      );
  }
  
  public void GetCount(Action&lt;int, Exception&gt; callback)
  {
      var callingThread = TaskScheduler.FromCurrentSynchronizationContext();
  
      Func&lt;int&gt; action = () =&gt;
      {
          return client.GetCount(); // Synchronous method, could take a long time
      };
  
      Action&lt;Task&lt;int&gt;&gt; completeAction = (task) =&gt;
      {
          Exception ex = (task.Exception != null) ? task.Exception.InnerException : task.Exception;
  
          if (callback != null)
              callback(task.Result, ex);
      };
  
      Task.Factory.StartNew(action).ContinueWith(completeAction, callingThread);
  }
  
  public void Get(Action&lt;object, Exception&gt; callback, int index)
  {
      var callingThread = TaskScheduler.FromCurrentSynchronizationContext();
  
      Func&lt;object&gt; action = () =&gt;
      {
          return client.Get(index); // Synchronous method, could take a long time
      };
  
      Action&lt;Task&lt;object&gt;&gt; completeAction = (task) =&gt;
      {
          Exception ex = (task.Exception != null) ? task.Exception.InnerException : task.Exception;
  
          if (callback != null)
              callback(task.Result, ex);
      };
  
      Task.Factory.StartNew(action).ContinueWith(completeAction, callingThread);
  }
  </code></pre>
  
  <p>In this way, each of my service's asynchronous methods would callback the thread they were originally called on (generally the UI thread).  So I am simulating how the await/async keywords work (I cannot use .NET 4.5).</p>
  
  <p>The problem with this pattern is that I get inexplicably locked to the UI thread after the first call to "ContinueWith".  So in this case if I attempt to spawn 5 threads to each process a synchronous function <strong>Get</strong>, they will execute 1 by 1 instead of in parallel and they will block the UI thread while doing so, even if I try specifying TaskCreationOptions.LongRunning.</p>
  
  <p>This never happens with my first call to Task.Factory.StartNew, it only happens to subsequent calls <strong>from within the first callback</strong>.</p>