开发者

.NET - multi-threaded iteration over a single List (Of T) - What do I need to watch out for?

I'm using VB.NET.

I want to build a large List (Of MyClassOrStructure) that becomes static after its initial population.

I'm going to have multiple threads that need to iterate through this list to read data (no writing, inserting, or deleting)

Are there any very bad things that I开发者_开发百科 need to keep an eye out for?

Thanks.


If you're just reading, you're fine. Each iterator will be independent of the others.

If you've ever wondered why the IEnumerable<T> interface doesn't directly have MoveNext() and Current, but instead has to create an IEnumerator<T> instance, that's why - the list itself doesn't keep the "cursor" saying where the iterator is, it's in the IEnumerator<T>. Sharing the IEnumerator<T> values between threads would almost certainly be a bad idea - but you're very unlikely to do that accidentally. The natural way of iterating on several threads will have one IEnumerator<T> per thread, which is safe (so long as you don't modify the list).


If the values are static, i cannot see any need for locking, but if it was ever to occur that you seldomly write to the object you can look at ReaderWriterLock Class


you obviously need some kind of locking, if both read and write are involved. the best approach is using a read-write lock. see ReaderWriterLockSlim.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜