当我正在研究框架的并行性时,我遇到了一个奇怪的情况,我无法想象为什么!我简化了情况来描述它很容易.
考虑这段代码:
考虑这段代码:
foreach(var person in personList) { if (person.Name == "Mehran") break; }
personList在多个线程之间共享.@H_403_6@
在什么情况下人可能为null,我得到person.Name的NullReferenceException?@H_403_6@
据我所知,这个人在这里被认为是一个局部变量,如果我们进入foreach块,所以我们已经成功迭代了personList,所以在任何情况下或任何并行场景中人都不应该为null.@H_403_6@
即使personList被另一个线程更改,或者被引用的人被处置,person变量也应该具有值.因为没有人可以更改引用此人的位置.@H_403_6@
是否有任何情况可以解释这种情况?@H_403_6@
解决方法
As I know,the person is considered as a local variable here and if the we get into the foreach block,so we have iterated the personList successfully,so person should not be null in any circumstances or any parallel scenario.@H_403_6@
仅仅因为你成功迭代personList并不意味着它不包含任何空值.例如:@H_403_6@
List<Person> personList = new List<Person>(); personList.Add(null); foreach (var person in personList) { // Here,person will be null }
(另外,如果有什么东西在修改列表,你通常会遇到麻烦 – 面对作者而言它们不是线程安全的 – 但我不认为这需要成为问题的一部分.)@H_403_6@