Toan Nguyen
Toan Nguyen

Reputation: 11591

What have I done wrong with Parallel.ForEach

I have the following code with Parallel.ForEach in C#

internal class Program
{
    private static void Main(string[] args)
    {
        var recordList = new List<string> {"1", "two", "three", "four", "five", "six"};

        var result = new ConcurrentBag<ProcessedData>();

        Parallel.ForEach<string, ProcessedData>(recordList, () => null //local init
            , (record, state, index, localInit) => //body
            {
                Console.WriteLine($"Processing {record}");
                var integerValue = record.Length;
                var processedString = record + " Processed";

                localInit = new ProcessedData
                {
                    IntegerValue = integerValue,
                    StringValue = processedString
                };

                return localInit;
            }, bodyResult => //local finally
            {
                Console.WriteLine($"Adding {bodyResult.StringValue}");
                result.Add(bodyResult);
            });


        foreach (var item in result)
        {
            Console.WriteLine($"{item.StringValue}");
        }

        Console.ReadLine();
    }

    private sealed class ProcessedData
    {
        internal int IntegerValue { get; set; }
        internal string StringValue { get; set; }
    }

When I run the program, I would expect that the console prints out "1 Processed", "two processed", "three Processed", "four Processed, "five Processed", "six Processed". However, instead only some items have been processed !!!

enter image description here

Do you know what went wrong with the code?

Upvotes: 1

Views: 199

Answers (1)

Servy
Servy

Reputation: 203829

The finally doesn't run that operation for every item in the collection. If you want to perform some operation for every item in the collection, that's what the body is for. The init and finally is for initialization and tear down of each worker thread. So your printouts are telling you that three threads were used in the processing of your items.

Upvotes: 4

Related Questions