.NET - Multi-threaded iteration over one list (Of T). What do I need to watch out for?
I am using VB.NET.
I want to create a large list (MyClassOrStructure) that will become static after its initial collection.
I will have multiple threads that need to iterate through this list to read data (no write, insert, or delete)
Are there any really bad things that I should watch out for?
Thank.
source to share
If you're just reading, that's okay. Each iterator will be independent of the others.
If you've ever wondered why an interface IEnumerable<T>
doesn't have a direct MoveNext()
and Current
, but instead must instantiate IEnumerator<T>
, so - the list itself doesn't store the "cursor" says where the iterator is at IEnumerator<T>
. Sharing values IEnumerator<T>
between threads is almost certainly a bad idea, but you are unlikely to do it by accident. The natural way to iterate over multiple threads would be to have one IEnumerator<T>
for each thread, which is safe (as long as you don't modify the list).
source to share
you clearly need some kind of locking if both read and write are involved. the best approach is to use read / write locks. see ReaderWriterLockSlim .
source to share