Parallel.ForEach - Access To Modified Closure Applies?

后端 未结 2 409
南旧
南旧 2021-01-14 00:57

I\'ve read a number of other questions about Access to Modified closure so I understand the basic principle. Still, I couldn\'t tell - does Parallel.ForEach hav

相关标签:
2条回答
  • 2021-01-14 01:30

    You are accessing a modified closure, so it does apply. But, you are not changing its value while you are using it, so assuming you are not changing the values inside UpdateUsageStats you don't have a problem here.

    Parallel.Foreach waits for the execution to end, and only then are you changing the values in startTime and endTime.

    0 讨论(0)
  • 2021-01-14 01:44

    "Access to modified closure" only leads to problems if the capture scope leaves the loop in which the capture takes place and is used elsewhere. For example,

    var list = new List<Action>();
    for (var i = 0; i < 7; i++)
    {
      list.Add(() => Console.WriteLine(i));
    }
    list.ForEach(a => a()); // prints "7" 7 times, because `i` was captured inside the loop
    

    In your case the lamda doing the capture doesn't leave the loop (the Parallel.ForEach call is executed completely within the loop, each time around).

    You still get the warning because the compiler doesn't know whether or not Parallel.ForEach is causing the the lambda to be stored for later invocation. Since we know more than the compiler we can safely ignore the warning.

    0 讨论(0)
提交回复
热议问题