I've read this patterns but found it not to work. I get a rare exception that an item in foreach was changed.
lock (mylist) { foreach(var a in myList) {}
myList = new List<>() (or myList.Clear() ) }
I also tried this
foreach(var a in myList.ToList() ) { }
And that also generated exceptions. There are some other patterns described in this thread but I want to confirm/understand why above patterns didnt work I've read a bit about how to properly lock a list. The exception doesn't occur often-- just very rarely and there was also a memory leak at the time.
1. Do I need to use the lock everywhere I modify myList or does the lock prevent anyone from editing mylist? This may be the source of confusion.
2.
Is there a difference in lock mylist and casting and using syncroot?
See here