列表是否可以被多个线程访问? [英] Can a List<t> be accessed by multiple threads?
问题描述
我打算在多个线程之间共享一个列表.该列表在更改期间会被锁定,这种更改很少发生.如果同时从列表中的不同线程进行多次迭代,是否存在线程安全问题?
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?
推荐答案
If you can (if you can use .NET 4 that is), use BlockingCollection<T>
:
为实现
IProducerConsumerCollection<T>
的线程安全集合提供阻止和绑定功能.
Provides blocking and bounding capabilities for thread-safe collections that implement
IProducerConsumerCollection<T>
.
如果没有,则完全封装该列表,并添加访问List<T>'s
状态的线程安全方法.不要公开引用该列表,也不要通过任何方法返回该列表-始终封装该引用,以确保可以锁定对它的所有访问.
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.
这篇关于列表是否可以被多个线程访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!