谈论System.Collections.Generic.List< T>这里.
下面的例子可以方法1和方法2执行同一时间,在不同的线程上没有任何问题?
谢谢
class Test { private readonly List<MyData> _data; public Test() { _data = LoadData(); } private List<MyData> LoadData() { //Get data from dv. } public void Method1() { foreach (var list in _data) { //do something } } public void Method2() { foreach (var list in _data) { //do something } } }
解决方法
是,列表< T>只要没有线程修改列表,就可以安全地从多个线程中读取.
从the docs:
A
List<T>
can support multiple
readers concurrently,as long as the
collection is not modified.
Enumerating through a collection is
intrinsically not a thread-safe
procedure. In the rare case where an
enumeration contends with one or more
write accesses,the only way to ensure
thread safety is to lock the
collection during the entire
enumeration. To allow the collection
to be accessed by multiple threads for
reading and writing,you must
implement your own synchronization.
(关于重复“本质上不是一个线程安全的过程”的观点是针对其他突变列表的).