How does local initialization with Parallel ForEach work?

后端 未结 4 976
暗喜
暗喜 2021-02-01 08:01

I am unsure about the use of the local init function in Parallel.ForEach, as described in the msdn article: http://msdn.microsoft.com/en-us/library/dd997393.aspx



        
4条回答
  •  时光取名叫无心
    2021-02-01 08:32

    From my side a little bit more easier example

    class Program
    {
        class Person
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
        }
    
        static List GetPerson() => new List()
        {
            new Person() { Id = 0, Name = "Artur", Age = 26 },
            new Person() { Id = 1, Name = "Edward", Age = 30 },
            new Person() { Id = 2, Name = "Krzysiek", Age = 67 },
            new Person() { Id = 3, Name = "Piotr", Age = 23 },
            new Person() { Id = 4, Name = "Adam", Age = 11 },
        };
    
        static void Main(string[] args)
        {
            List persons = GetPerson();
            int ageTotal = 0;
    
            Parallel.ForEach
            (
                persons,
                () => 0,
                (person, loopState, subtotal) => subtotal + person.Age,
                (subtotal) => Interlocked.Add(ref ageTotal, subtotal)
            );
    
            Console.WriteLine($"Age total: {ageTotal}");
            Console.ReadKey();
        }
    }
    

提交回复
热议问题