【发布时间】:2017-03-10 13:20:50
【问题描述】:
lock关键字用于你想实现该区域最多由线程执行的地方,在多线程环境中,其余线程将等待该区域。
我有一个集合IList<Student> student=new List<Student>() 正在多个类中使用。
在某些地方,对象被添加到列表中,而在某些地方,对象被删除。这会导致一些不一致的行为。
当我在多线程环境中锁定类 x 中的集合时,是否会为所有类锁定该集合,并且不同类中的所有线程都会等待锁定?
Class StaticClass
{
Public static IList<Student> student=new List<Student>();
}
Class ClassA
{
//add an item in the collection
}
Class ClassB
{
//delete an item in the collection
}
Class ClassC
{
//lock the collection here
lock (StaticClass.student)
{
foreach (ConnectionManager con in ConnectionManager.GetAllStudents())
{
con.Send(offlinePresence);
}
}
}
当我将集合锁定在 ClassC 中时,classA 和 ClassB 的其他线程会等待吗?直到 for 循环执行没有人被允许添加或删除集合中的项目,因为集合已被锁定?
【问题讨论】:
-
基本上是的,但是最好有一个单独的
static readonly object用于锁定而不是使用列表(或创建列表readonly),以便在锁定时不能更改引用的对象 -
For 循环您可以创建列表的副本(新实例),然后在循环期间添加、删除类不会影响。
foreach(var student in students.ToList())... -
您必须使用
lockEVERYWHERE...每次您访问该集合以任何方式您必须锁定它。StaticClass.student.Count?lock!StaticClass.student[0]?lock! -
有关@slawekwin 评论的更多信息,请参见stackoverflow.com/questions/251391/why-is-lockthis-bad。
标签: c# multithreading locking