Click here to Skip to main content
12,297,275 members (63,556 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C#
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);

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 5-Dec-12 2:03am
Edited 5-Dec-12 4:27am
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

I'm not entirely sure if this is exactly what you need, but Parallel Aggregation[^] might be your solution.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

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>.
const int count = 10;
double[] results = new double[count];
Parallel.For(0, count, i => { results[i] = SumRootN(i, "t"); });
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160525.2 | Last Updated 5 Dec 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100