Parallel.ForEach - 访问要修改的封闭应用? [英] Parallel.ForEach - Access To Modified Closure Applies?

查看:225
本文介绍了Parallel.ForEach - 访问要修改的封闭应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一些有关访问修改关闭其他问题我是这么理解的基本原则。不过,我不知道 - 不 Parallel.ForEach 有同样的问题。

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 have the same issues?

看看下面的代码片段,我重新计算使用情况统计信息,为用户的最后一个星期作为一个例子:

Take the following snippet where I recompute the usage stats for users for the last week as an example:

var startTime = DateTime.Now;
var endTime = DateTime.Now.AddHours(6);
for (var i = 0; i < 7; i++)
{
    // this next line gives me "Access To Modified Closure"
    Parallel.ForEach(allUsers, user => UpdateUsageStats(user, startTime, endTime));

    // move back a day and continue the process
    startTime = startTime.AddDays(-1);
    endTime = endTime.AddDays(-1);
}

据我所知这$ C C $的的foreach 应该运行我的 UpdateUsageStats 常规马上和启动/结束时间的变量将不被更新,直到围绕该环路的下一次。那是正确的,或者我应该使用局部变量,以确保不会有问题?

From what I know of this code the foreach should run my UpdateUsageStats routine right away and start/end time variables won't be updated till the next time around the loop. Is that correct or should I use local variables to make sure there aren't issues?

推荐答案

您的访问修改关闭,所以也适用。 但是,你不改变它的价值,而你在使用它,所以假设你是不是在 UpdateUsageStats 更改值你没有一个问题就在这里。

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 等待执行的结束,也只有这样,你的的startTime 更改值和 endTime的

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

这篇关于Parallel.ForEach - 访问要修改的封闭应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆