5

As you can guess the index of the Parallel.For() loop jumps from one value to the other. How can I estimate the amount of the work done?

Thanks.

abenci
  • 8,422
  • 19
  • 69
  • 134

2 Answers2

7

By keeping a counter rather than looking at the index? For example:

int counter  = 0;
Parallel.For(4, 500, i => {
    // TODO: something useful...         
    int progress = Interlocked.Increment(ref counter);
    Console.WriteLine("{0}: {1}", progress, i);
});

(the Interlocked usage is essential to avoid getting race-conditions on accessing counter)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3
int progress = 0;
Parallel.For( from, to, i => {
// do the job
Interlocked.Increment(ref progress);
});

now actual progress is (float)(to - from) / progress

Andrey
  • 59,039
  • 12
  • 119
  • 163
  • No way to get this value without interfering with thread synchronization? – abenci Oct 21 '10 at 10:18
  • @devdept no. but what is the problem using this method? – Andrey Oct 21 '10 at 11:26
  • I thought the the Parallel.For() included a more elegant way to get this value. – abenci Oct 21 '10 at 14:04
  • @devdept you have to add two lines of code, what is not elegant here? – Andrey Oct 21 '10 at 14:14
  • @Alberto, [here](https://gist.github.com/0xorial/8b82594e8f2b96beae77) is a wrapper that incapsulates threading stuff. It is important to use value returned by 'Increment' though, otherwise you may still get race conditions. – ironic Nov 24 '14 at 09:23