在对集合进行线程间的操作时要分外小心,集合属性开放可写操作。由于集合是引用类型,在两个线程中改变同一个集合,可能会导致另一个线程访问时出错。
class Student { public string Name { get; set; } public int Age { get; set; } }
class StudentTeamA { public List<Student> Students { get; set; } }
class Program { static List<Student> studentList = new List<Student>() { new Student(){Name = "Janeliy",Age = 19}, new Student(){Name = "Machial",Age = 22} }; static void Main(string[] args) { StudentTeamA studentTeamA = new StudentTeamA(); Thread thread01 = new Thread(() => { studentTeamA.Students = studentList; Thread.Sleep(1000); Console.WriteLine(studentList.Count); // 模拟对集合属性进行运算 }); thread01.Start(); Console.WriteLine("Hello World!"); Thread thread02 = new Thread(() => { studentList = null; }); thread02.Start(); } }
上面是第一次对集合属性进行操作。
在上面对集合的运算,因为是线程对“当集合成为属性时的可写方法进行限制”,所以我认为不应该是对外面的studentList集合进行修改;改成对studentTeamA.Students的修改和输出,结果都是为null。
下面对StudentTeamA进行修改:限制了写方法,但还是开放了对其list集合的赋值。
class StudentTeamA { public List<Student> Students { get; private set; } public StudentTeamA() { Students = new List<Student>(); } public StudentTeamA(IEnumerable<Student> studentList) : this() { Students.AddRange(studentList); } }
总结:该篇的主旨思想就是告诉我们,集合属性不能随便开放写操作。
标签:Students,studentList,谨慎,StudentTeamA,集合,new,public,属性 From: https://www.cnblogs.com/wen-chen/p/16988703.html