increment a count value outside parallel.foreach scope

后端 未结 4 864
一整个雨季
一整个雨季 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:41

    Use Interlocked.Increment method in this way.

    int count = 0;
    Parallel.ForEach(users, (u) =>
    {
        var currentCount = Interlocked.Increment(ref count);
        Log(String.Format("Step {0} of {1}", currentCount, users.Count));
    });
    

提交回复
热议问题