How to synchronize parallel actions in .NET?

I would like to accomplish the following:

void Method()
{
    Parallel.For(0, 100, i =>
    {
        // Do first set of actions

        // Wait for all tasks to finish performing first set of actions

        // Do second set of actions
    });
}

I cannot simply do

void Method()
{
    Parallel.For(0, 100, i =>
    {
        // Do first set of actions
    });

    Parallel.For(0, 100, i =>
    {
        // Do second set of actions
    });
}

because each task instantiates a new object in the first set of actions, and the second set of actions must be able to reference that instance.

How can I accomplish this?

Jon Skeet
people
quotationmark

I would suggest you do exactly as per your second code snippet, but keep an array for these newly created objects - populate them in the loop, and access them in the second.

void Method()
{
    var intermediates = new Intermediate[100];
    Parallel.For(0, 100, i =>
    {
        // ...
        intermediates[i] = ...;
    });

    Parallel.For(0, 100, i =>
    {
        var intermediate = intermediates[i];
        // ... use intermediate
    });
}

people

See more on this question at Stackoverflow