加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 通过另一个线程将局部变量修改为null,这怎么可能

发布时间:2020-12-15 17:40:40 所属栏目:百科 来源:网络整理
导读:当我正在研究框架的并行性时,我遇到了一个奇怪的情况,我无法想象为什么!我简化了情况来描述它很容易. 考虑这段代码: foreach(var person in personList){ if (person.Name == "Mehran") break;} personList在多个线程之间共享. 在什么情况下人可能为null,
当我正在研究框架的并行性时,我遇到了一个奇怪的情况,我无法想象为什么!我简化了情况来描述它很容易.
考虑这段代码:
foreach(var person in personList)
{
    if (person.Name == "Mehran")
        break;
}

personList在多个线程之间共享.

在什么情况下人可能为null,我得到person.Name的NullReferenceException?

据我所知,这个人在这里被认为是一个局部变量,如果我们进入foreach块,所以我们已经成功迭代了personList,所以在任何情况下或任何并行场景中人都不应该为null.

即使personList被另一个线程更改,或者被引用的人被处置,person变量也应该具有值.因为没有人可以更改引用此人的位置.

是否有任何情况可以解释这种情况?

解决方法

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.

仅仅因为你成功迭代personList并不意味着它不包含任何空值.例如:

List<Person> personList = new List<Person>();
personList.Add(null);

foreach (var person in personList)
{
   // Here,person will be null
}

(另外,如果有什么东西在修改列表,你通常会遇到麻烦 – 面对作者而言它们不是线程安全的 – 但我不认为这需要成为问题的一部分.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读