title: Multithreading iterative-intensive work
body: <p>I'm creating a game with loads of asteroids floating in a huge space. To accomodate the heavy collision detection, I've split the world into "AsteroidChunks" where only the closest chunks are being used for collision detection. The work to split up the asteroids into the chunks is extremely repetitive with something like 1.2 billion iterations made every time the game starts up. However, I've noticed that the game is not actually using that much CPU power. Not a single core was running at 100%! (The game is based on MonoGame for Windows)</p>
  
  <p>My idea is that by running the most iterative-heavy stuff on multiple threads (something like giving each thread 1000 iterations to complete) I would be able to get the job done quicker, at the expense of CPU power of course. Am I on the right track, and how should I proceed?</p>
  
  <p>Is there any other way of speeding up the iterations, allowing for a larger 3D space?</p>
  
  <p>This is what I've tried so far. It's not working, but gives an idea of what I want to accomplish: (<code>asteroidChunks</code> is a <code>List</code> with approx. 16,000 entries, but could easily be > 100,000))</p>
  
  <pre><code>Task[] populateChunkTasks = new Task[asteroidChunks.Count];
  
  for (int i = 0; i &lt; asteroidChunks.Count; i += 1000)
     populateChunkTasks[i] = new Task(() =&gt;
      {
          for (int x = i; x &lt; asteroidChunks.Count &amp;&amp; x &lt; i + 1000; x++)
              PopulateChunk(asteroidChunks[x]);
      });
  
  for (int i = 0; i &lt; populateChunkTasks.Length; i++)
      populateChunkTasks[i].Start();
  
  Task.WaitAll(populateChunkTasks);
  </code></pre>
  
  <p>As you can see I want to wait for the threads to complete at the end. However, the operation itself is in its own <code>Task</code>, which is why I can't wait for all tasks - in this case - to complete before proceeding.</p>
  
  <p><code>PopulateChunk</code>: (<code>asteroidList</code> is a list with approx 75,000 entries, but could easily be > 1million)</p>
  
  <pre><code>public static AsteroidChunk PopulateChunk(AsteroidChunk chunk)
  {
      foreach (Asteroid asteroid in asteroidList)
          if (chunk.box.Contains(asteroid.boundingSphere) == ContainmentType.Contains)
              chunk.asteroids.Add(asteroid);
  
      return chunk;
  }
  </code></pre>