title: High CPU usage in C# multi-threaded code
body: <p>I don't have much knowledge in writing good multi-threaded code. I have just recently started working on a project where it is necessary. I have written the following code, which works as I want it to, however, the CPU usage is very high. I am assuming it is due to how I am using the threads. If anyone could point out the flaw in the below code and let me know how to fix it so the CPU usage is not so high, I would greatly appreciate it.</p>
  
  <pre class="lang-cs prettyprint-override"><code>var numberOfMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["NumberOfMinutesToRun"]);
  var traversals = DbLayer.GetTraversals().ToList();
  var numberOfThreads = Convert.ToInt32(ConfigurationManager.AppSettings["NumberOfThreads"]);
  var threads = new List&lt;Thread&gt;(numberOfThreads);
  var counter = 1;
  var s = new Stopwatch();
  s.Start();
  var sync = new object();
  while (s.Elapsed &lt; TimeSpan.FromMinutes(numberOfMinutes))
  {
      for (var i = 0; i &lt; (numberOfThreads - threads.Count); i++)
      {
          var counter1 = counter; // due to closure.
          var traversal = traversals.FirstOrDefault(t =&gt; t.Id == counter1);
          var threadStart = new ThreadStart(new CallHelper(traversal).Migrate);
          var i1 = i;
          threadStart += () =&gt;
                         {
                              threads.RemoveAt(i1);
                         };
          threads.Insert(i, new Thread(threadStart) {IsBackground = true});
          threads[i].Start();
          lock (sync)
          {
              counter++;
              if (counter &gt; 6)
              {
                  counter = 1;
              }
          }
      }
  }
  s.Stop();
  </code></pre>
  
  <p>I updated the code to show, what I hope, is required to help me. The traversals collection contains only 6 items. The counter is there to ensure that the threads rotate through each of the 6 items in the traversals collection. The CallHelper class is just performing a very long running task on each traversal. The application is designed to perform the long running task on 6 different objects using a configurable amount of threads for a configurable amount of time. Hopefully I have filled in enough of the blanks.</p>