我有这两个看似相同的循环的实现:
List<Type> types = ...
tasks = new Task<List<TypeInfo>>[types.Count];
for (Int32 i = 0; i < types.Count; i++)
{
tasks[i] = Task<List<TypeInfo>>.Run(() => GetBaseTypeList(types[i]));
}
Task.WaitAll(tasks);
当我这样做时,我可能会得到一个 IndexOutOfRangeException
,因为当异步任务启动时,i
现在可能有任何值。
到目前为止,我确实了解其背后的机制。
我不明白的是,为什么会这样:
List<Type> types = ...
tasks = new Task<List<TypeInfo>>[types.Count];
for (Int32 i = 0; i < types.Count; i++)
{
Type t;
//do not put the indexer types[i] directly into the call because when the task is executed, i can have any value (delayed execution!).
t = types[i];
tasks[i] = Task<List<TypeInfo>>.Run(() => GetBaseTypeList(t));
}
Task.WaitAll(tasks);
t
在每个循环中也会发生变化,但为什么所有任务都使用在该循环迭代期间分配的 t
完美执行?
最佳答案
t
在循环中没有改变。
t
是 for
循环范围内的局部变量,这基本上意味着它是每次迭代的"new" t
.
i
存在于 for
循环的所有迭代中(否则每次迭代都会为 0),超过这个值就是为什么它在每次迭代中都发生变化并且不应该关闭。
例如,在 Type t;
之后的第二次迭代中,t
的值为 null
而不是上一次迭代的类型。
关于c# - 为什么值类型和引用类型在任务循环中表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27427933/