user3587624
user3587624

Reputation: 1471

Parallel.For with custom data type: Update variable outside of the loop

I am trying to write some code based on the answer provided in this question. The thing is that in my case I have my own custom data type and I am not using an integer.

How can I do a Parallel.For with a custom data?

This is the answer provided in the linked question

Parallel.For<int>(0, 1000, () => 0, (res, loop, subtotal) =>
            {
                subtotal += 1;
                return subtotal;
            },
            (x) => Interlocked.Add(ref sum, x)
            );

And this is how I am doing my loop without using Parallel.

int value1 = 0;
int value2 = 0;
List<MyData> myDataTypeList = ...
foreach (var myDataType in myDataTypeList)
{
         value1 = value1 + Function1(myDataType);
         value2 = value2 + Function2(myDataType);
}

Is there a way I can transform my non-parallel loop into a Parallel.For similar to the response provided in the other question?

Upvotes: 0

Views: 254

Answers (1)

Roger Leblanc
Roger Leblanc

Reputation: 1583

You'll need to use an object instead of int for your TLocal variable.

        int value1 = 0;
        int value2 = 0;

        //Populate data
        List<MyDataType> list = new List<MyDataType>();
        for (int i = 1; i < 5; i++)
            list.Add(new MyDataType { SomeProp = i });

        Parallel.For(
            0, //Start of loop
            list.Count, //End of loop
            () => new SomeObject { Number1 = 0, Number2 = 0 }, //Initializer
            (i, loop, subtotal) =>
            {
                //
                subtotal.Number1 += Function1(list[i]);
                subtotal.Number2 += Function2(list[i]);
                return subtotal;
            }, //Logic
            (x) =>
            {
                Interlocked.Add(ref value1, x.Number1);
                Interlocked.Add(ref value2, x.Number2);
            }//Finally
        );

I've created a dummy SomeObject class just for using multiple variables inside the Parallel.For.

public class SomeObject
{
    public int Number1 { get; set; }
    public int Number2 { get; set; }
}

Upvotes: 1

Related Questions