title: parallel foreach loop - odd behavior
body: <p>The code below simply creates a List> of random numbers and then calculates the cumulative sum of each list in a parallel foreach loop. Why do I get less than 'numLists' evaluations? Often around 9990. I'm guessing it has something to do with thread safety. What's an alternative method? (I'm a C# beginner so hopefully I'm using correct terms) Thanks.</p>
  
  <pre><code>using System;  
  using System.Collections.Generic;  
  using System.Threading.Tasks;  
  
  namespace testParallelForeach
  {
      class Program
      {
          static void Main(string[] args)
          {
  
              List&lt;List&lt;double&gt;&gt; bsData = new List&lt;List&lt;double&gt;&gt;();
              List&lt;List&lt;double&gt;&gt; cumsumDataP = new List&lt;List&lt;double&gt;&gt;();
              int numLists = 10000;
              int myLen = 400;
              Random rand = new Random();
              for (int i = 0; i &lt; numLists; i++)
              {
                  bsData.Add(new List&lt;double&gt;());
                  for (int j = 0; j &lt; myLen; j++)
                  {
                      bsData[i].Add(rand.NextDouble());
                  }
              }
              Parallel.ForEach(bsData, a =&gt; cumsumDataP.Add(CumulativeSumParallel(a)));
              Console.WriteLine("cumsumDataP.Count={0}", cumsumDataP.Count);
              Console.ReadKey();
  
          }
  
          public static List&lt;double&gt; CumulativeSumParallel(List&lt;double&gt; singleRetSeries)
          {
              int r = singleRetSeries.Count;
              List&lt;double&gt; cumsumList = new List&lt;double&gt;();
  
              cumsumList.Add(singleRetSeries[0]);
              for (int i = 1; i &lt; r; i++)
              {
                  cumsumList.Add(cumsumList[i - 1] + singleRetSeries[i]);
              }
              return cumsumList;
          }
      }
  }
  </code></pre>