increment a count value outside parallel.foreach scope

后端 未结 4 841
一整个雨季
一整个雨季 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 07:45

    Use Interlocked.Increment.

    I wouldn't increment things inside a parallel foreach (unless, of course, you're using Interlocked.Increment or some other locking mechanism). That's not what it's for. The Parallel foreach should be run only with actions that cause no side effects in shared state. To increment a value in a parallel foreach will cause the very problem you're more than likely trying to avoid.

提交回复
热议问题