title: Parallel recursion in c#
body: <pre><code>    class CustomData
      {
         public int TNum;
         public int TResult;
      }
  
      public static int F_recursion(int n, int w)
      {
          if (n == 0 || w == 0)
              return 0;
          else if (s[n] &gt; w)
              return F_recursion(n - 1, w);
          else
          {
              return Math.Max(F_recursion(n - 1, w), p[n] + F_recursion(n - 1, w - s[n]));
          }
      }
  
      public static int F_recursion2(int n, int w)
      {
          int numba = 0;
          int countCPU = 8;
          Task[] tasks = new Task[countCPU];
            for (var j = 0; j &lt; countCPU; j++)
              tasks[j] = Task.Factory.StartNew(
                 (object p) =&gt;
                 {
                   var data = p as CustomData; if (data == null) return;
                     data.TResult = F_recursion(n - data.TNum, w);
                 },
              new CustomData() { TNum = j });
            Task.WaitAll(tasks);
            numba = (tasks[0].AsyncState as CustomData).TResult
            + (tasks[1].AsyncState as CustomData).TResult
            + (tasks[2].AsyncState as CustomData).TResult
            + (tasks[3].AsyncState as CustomData).TResult;
  
          return numba;
      }
  </code></pre>
  
  <p>How could i make F_recursion2 method to work in parallel? With my code current results are</p>
  
  <pre><code>Time in milliseconds for recursion:  1,075
  recursion(  150 ) =     7,237
  Time in milliseconds for parallel recursion:  1,581
  recursion(  150 ) =    28,916
  </code></pre>
  
  <p>As you can see parallel approach prints 4 times bigger number and it takes more time to compute which doesn't make sense. How could I approach this problem that recursion would work in parallel?</p>
  
  <p><strong>EDIT</strong> Changed for loop to Parallel.For still same results as above.</p>
  
  <pre><code>    public static int F_recursion2(int n, int w)
      {
          int numba = 0;
          int countCPU = 8;
          Task[] tasks = new Task[countCPU];
          Parallel.For(0, countCPU, j =&gt;
         {
             tasks[j] = Task.Factory.StartNew(
                (object p) =&gt;
                {
                    var data = p as CustomData; if (data == null) return;
                    data.TResult = F_recursion(n - data.TNum, w);
                },
             new CustomData() { TNum = j });
         });
          Task.WaitAll(tasks);
          numba = (tasks[0].AsyncState as CustomData).TResult
          + (tasks[1].AsyncState as CustomData).TResult
          + (tasks[2].AsyncState as CustomData).TResult
          + (tasks[3].AsyncState as CustomData).TResult;
  
          return numba;
      }
  </code></pre>