How to calculate completion percentage in the parallel for?

With for calculating the completion percentage is easy:

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        // Do somethings...
        Console.WriteLine("{0}% Done!", i * 10 + j + 1);
    }
}

Output:

1% Done!
2% Done!
3% Done!
4% Done!
5% Done!
6% Done!
7% Done!
8% Done!
9% Done!
10% Done!
11% Done!
12% Done!
13% Done!
...
93% Done!
94% Done!
95% Done!
96% Done!
97% Done!
98% Done!
99% Done!
100% Done!

But I don't have any idea about the calculating completion percentage with Parallel.For:

Parallel.For(0, 10, i =>
{
    Parallel.For(0, 10, j =>
    {
        // Do somethings...
        Console.WriteLine("{0}% Done!", i * 10 + j + 1);
    });
});

Output:

1% Done!
2% Done!
3% Done!
51% Done!
52% Done!
53% Done!
54% Done!
55% Done!
56% Done!
57% Done!
58% Done!
59% Done!
60% Done!
4% Done!
5% Done!
6% Done!
...
69% Done!
70% Done!
71% Done!
72% Done!
73% Done!
74% Done!
75% Done!
76% Done!
77% Done!
78% Done!
79% Done!
80% Done!
36% Done!
37% Done!
38% Done!
39% Done!
40% Done!
35% Done!

The output is not shown the correct completion percentage.

How to calculate completion percentage in the Parallel.For without reduce the performance?

Answers


You can use Interlocked.Increment method for that:

int progress = 0;
Parallel.For(0, 10, i =>
{
    Parallel.For(0, 10, j =>
    {
        // Do somethings...
        Console.WriteLine("{0}% Done!", Interlocked.Increment(ref progress));
    });
});

There will be one increment per iteration of the inner loop. Some printouts may appear out of sequence - specifically, when a thread is preempted after obtaining the new value of the progress but before the printing is complete.


For a simple case like this when you know that you're processing exactly 100 items, just have an outer variable that you (thread safely) increment and report on:

int progress = 0;
Parallel.For(0, 10, i =>
{
    Parallel.For(0, 10, j =>
    {
        // Do somethings...
        Console.WriteLine("{0}% Done!", Interlocked.Increment(ref progress));
    });
});

But note that you may still get some values reported out of order (since parallel tasks will perform the increment and then have to compete for access to the Console, which is an exclusive resource)


Need Your Help

How do I use an edit viewmodel in MVC?

asp.net-mvc database entity-framework mvvm

I have been struggling with this for some time. I have a model and an edit view model so I can allow the user to both see the image that was uploaded before and upload a replacement. Everything works

Moving data in excel from a column to rows based on criteria of column

excel excel-vba vba

I have a spreadsheet that has a column of information ie: