The lock
keyword is used where you want to achieve that the area should be executed by at most on thread, in a multithreading environment, rest of the thread will wait for the area.
I have a collection IList<Student> student=new List<Student>()
that is being used in multiple classes.
In some places objects are getting added to the list, and in some places objects are getting deleted. This causes some inconsistent behavior.
Is it true that when I lock the collection in class x in a multithreading environment, the collection will be locked for all classes and all threads in different classes will wait for the lock?
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);
}
}
}
When I have locked the collection in ClassC, will other threads for classA and ClassB wait? Until the for loop execute nobody is allowed to add or delete items in the collection, because the collection has been locked?