I am wondering how to properly lock the getter of type List
. I have one static class that looks something like this:
class FirstClass {
static private locker = new object();
static private List<String> _my_list;
public static List<String> my_list {
get {
lock(locker) {
return my_list;
}
}
}
private static void thread_func() {
// do something periodicaly with the list
// for example:
lock(locker){
_my_list.Add();
_my_list.RemoveAt();
...
}
}
}
Then, I have another class that looks like this:
class SecondClass {
private void thread_func() {
foreach(string s in FirstClass.my_list) {
// read every item in the list
}
}
}
So, first class has a public list that the second class uses. First class periodically updates the list in one thread, and second class reads the list at an random interval on a second thread.
Does this locking mechanism ensure that the list will not be modified by the first class while the second class is reading it and vice-versa?