Click here to Skip to main content
15,906,094 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
How do I save the results of the method called in the parallel loop that returns a double result to a list? Each time the method is run it returns a result. I want to add that specific result to a list.

Stopwatch sw = new Stopwatch();
     sw.Start();
     for (int i = 0; i < 10; i++)
     {
         SumRootN(i,"t");
     }
     sw.Stop();

     Stopwatch sw2 = new Stopwatch();
     sw2.Start();


     //NEED TO SAVE RESULTS TO LIST
     Parallel.For(0, 10, i => SumRootN(i,"t"));


     sw2.Stop();
     double t = sw2.ElapsedTicks;
     Console.WriteLine("Seq " + sw.ElapsedMilliseconds);
     Console.WriteLine("Parallel " + sw2.ElapsedMilliseconds);


C#
public static double SumRootN(int root,string test)
       {

           double result = 0;
           for (int i = 1; i < 1000000; i++)
           {
               result += Math.Exp(Math.Log(i) / root);

           }
           return result;
       }
Posted
Updated 5-Dec-12 4:27am
v2

I'm not entirely sure if this is exactly what you need, but Parallel Aggregation[^] might be your solution.
 
Share this answer
 
shekarchee is close, but if you need to keep the results in the same sequence as if it was NOT performed in parallel, then the simplest is to use an array instead of the List<double>.
C#
const int count = 10;
double[] results = new double[count];
Parallel.For(0, count, i => { results[i] = SumRootN(i, "t"); });
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900