Why does this lock statement not work?

why does this lock test not work? he throws an exception below Console.Write that the collection has been modified ....

static List<string> staticVar = new List<string>(); static void Main(string[] args) { Action<IEnumerable<int>> assyncMethod = enumerator => { lock (staticVar) foreach (int item in enumerator) staticVar.Add(item.ToString()); }; assyncMethod.BeginInvoke(Enumerable.Range(0, 500000), null, null); Thread.Sleep(100); Console.Write(staticVar.Count()); foreach (string item in staticVar) { } } 
+4
source share
1 answer

For locking to be effective, it must be used in all cases when access to the collection is made. Whether it is reading or writing. So you must add a lock before listing the collection

for instance

 lock (staticVar) { Console.Write(staticVar.Count()); foreach (string item in staticVar) { } } 
+5
source

Source: https://habr.com/ru/post/1310408/


All Articles