Alex Rivera | Logout

Can a List<t> be accessed by multiple threads?

Asked 2010-12-21T21:58:35.027
16

I am planning to share a List between multiple threads. The list will be locked during a changes, which happen infrequently. Is there a thread safety issue if multiple iterations are made from different threads through the list simultaneously?

Edit
Report

1 Answer

13

If you can (if you can use .NET 4 that is), use BlockingCollection<T>:

Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection<T>.

If not then encapsulate the list completely and add thread-safe methods that access the List<T>'s state. Don't make the reference to the list public or return it from any methods - always encapsulate the reference so you can guarantee that you are locking around all access to it.

answered 2010-12-21T22:00:16.583

Your Answer