increment a count value outside parallel.foreach scope

后端 未结 4 830
一整个雨季
一整个雨季 2020-12-03 07:18

How can I increment an integer value outside the scope of a parallel.foreach loop? What\'s is the lightest way to synchronize access to objects outside parallel loops?

4条回答
  •  自闭症患者
    2020-12-03 08:04

    Parallel.Foreach comes along with an extra overload that perfectly fits for that kind of scenario when you just want to count things inside the loop.

        int totalCount = 0;
        Parallel.ForEach(files, () => 0, (file, loopState, localCount) =>
        {
            if(ProcessFile(file))
               localCount++;
        
            return localCount;
        
        }, localCount => Interlocked.Add(ref totalCount, localCount));
    
        Console.WriteLine($"Processed {totalCount}/{files.Length} files.");
    

    Into the loop body you can inject a thread local count varialble and increment/decrement it as usual. This way you do not have an InterLocked call in every loop cycle. Instead there is just one Interlocked.Add call at the end of each parallel Task summing up totalCount.

    Note that with this method you should not use totalCount from within the loop body. If your problem requires to access totalCount from within the loop body you have to use the InterLocked.Incerment method as describe in other answers.

提交回复
热议问题