Guest User

Untitled

a guest
Jul 20th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. async Task<double> ComputeStuffAsync(CancellationToken token)
  2. {
  3. var tsk = Task.Run(() =>
  4. {
  5. var sum = 0.0;
  6. int DOP = 4;
  7.  
  8. Parallel.For(0, DOP - 1, new ParallelOptions { MaxDegreeOfParallelism = DOP, CancellationToken = token },
  9. // Initialize the local states
  10. () => (double)0.0,
  11. // Accumulate the thread-local computations in the loop body
  12. (thread, loop, localState) =>
  13. {
  14. long from = 1 + (thread * 100 * 1000 * 1000);
  15. long to = ((thread + 1) * 100 * 1000 * 1000);
  16.  
  17. var computed = Calc(from, to);
  18. return localState + computed;
  19. },
  20. // Combine all local states
  21. localState => Interlocked.Exchange(ref sum, localState)
  22. );
  23.  
  24. return sum;
  25. }, token);
  26.  
  27. return await tsk;
  28.  
  29. double Calc(long from, long to)
  30. {
  31. double sum = 0;
  32. for (long i = from; i < to; i++)
  33. sum += Math.Sqrt(i);
  34. return sum;
  35. }
  36. }
Add Comment
Please, Sign In to add comment