Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async Task<double> ComputeStuffAsync(CancellationToken token)
- {
- var tsk = Task.Run(() =>
- {
- var sum = 0.0;
- int DOP = 4;
- Parallel.For(0, DOP - 1, new ParallelOptions { MaxDegreeOfParallelism = DOP, CancellationToken = token },
- // Initialize the local states
- () => (double)0.0,
- // Accumulate the thread-local computations in the loop body
- (thread, loop, localState) =>
- {
- long from = 1 + (thread * 100 * 1000 * 1000);
- long to = ((thread + 1) * 100 * 1000 * 1000);
- var computed = Calc(from, to);
- return localState + computed;
- },
- // Combine all local states
- localState => Interlocked.Exchange(ref sum, localState)
- );
- return sum;
- }, token);
- return await tsk;
- double Calc(long from, long to)
- {
- double sum = 0;
- for (long i = from; i < to; i++)
- sum += Math.Sqrt(i);
- return sum;
- }
- }
Add Comment
Please, Sign In to add comment