title: Is it possible always to force a new thread with Task?
body: <p>I am trying to create a new thread each time <code>Task.Factory.StartNew</code> is called. The question is how to run the code bellow without throwing the exception:</p>
  <pre><code>static void Main(string[] args)
  {
      int firstThreadId = 0;
  
      Task.Factory.StartNew(() =&gt; firstThreadId = Thread.CurrentThread.ManagedThreadId);
  
      for (int i = 0; i &lt; 100; i++)
      {
          Task.Factory.StartNew(() =&gt;
          {
              while (true)
              {
                  Thread.Sleep(1000);
                  if (firstThreadId == Thread.CurrentThread.ManagedThreadId)
                      throw new Exception(&quot;The first thread is reused.&quot;);
              }
          });
      }
      Console.Read();
  }
  </code></pre>
  <p><strong>EDIT: the new code</strong> if you comment the first <code>for</code> statement there is no problem. But if you have it, WOW, the message &quot;Thread reused&quot; is written to the console. Can you explain that because I am really confused.</p>
  <pre><code>static void Main(string[] args)
  {
      ConcurrentDictionary&lt;int, int&gt; startedThreads = new ConcurrentDictionary&lt;int, int&gt;();
  
      for (int i = 0; i &lt; 10; i++)
      {
          Task.Factory.StartNew(() =&gt;
          {
              Task.Factory.StartNew(() =&gt;
              {
                  startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId,
                      Thread.CurrentThread.ManagedThreadId, (a, b) =&gt; b);
              }, TaskCreationOptions.LongRunning);
  
              for (int j = 0; j &lt; 100; j++)
              {
                  Task.Factory.StartNew(() =&gt;
                  {
                      while (true)
                      {
                          Thread.Sleep(10);
                          if (startedThreads.ContainsKey(
                              Thread.CurrentThread.ManagedThreadId))
                                  Console.WriteLine(&quot;Thread reused&quot;);
                      }
                  }, TaskCreationOptions.LongRunning);
              }
          });
      }
  
      Console.Read();
  }
  </code></pre>