Willem
Willem

Reputation: 9486

Parallel.ForEach finally clause

I would like to know if there is maybe a finally that i can use in a Parallel.ForEach?

try
{
}
finally
{
}

Is this possible in a Parallel.ForEach?

I need to do a finally when the loop has completed.

Parallel.ForEach(someList, x =>
{
    //...
}, // Now i need to do a finally);

My problem is that i have a try finally around my Parallel.ForEach, but i dont want the finally to happen. It must only happen when the parallel task has completed.

So this does not work for me:

try
{
   Parallel.ForEach(someList, x =>
   {
      //...
   });
}
finally
{
}

Is there maybe another way of doing this?

Upvotes: 1

Views: 1678

Answers (2)

Christian.K
Christian.K

Reputation: 49260

Loops and finally don't go together (except maybe in Python). You simply write the code to run after the loop, well, after the loop.

If you want to run it regardless of exceptions in the loop, do it like this:

try
{
   Parallel.ForEach(...)
}
finally
{
   // ...
}

On second thought, maybe the OP ment to use this Parallel.ForEach overload, which allows you to provide a "localFinal" action, that is invoked whenever a thread (used to execute one more iterations of the loop) has completed.

Upvotes: 5

David M
David M

Reputation: 72880

You either put a try .. finally block inside the action being performed in parallel, or outside it:

Parallel.ForEach(someList, x =>
{
    try
    {
    }
    finally
    {
    }
});

or:

try
{
    Parallel.ForEach(someList, x =>
    {
    });
}
finally
{
}

It depends on your use case, which isn't clear from the question.

Upvotes: 2

Related Questions