c# - C# List<T> 的线程安全给读者

标签 c# list thread-safety generic-list

我计划在静态构造函数中创建一次列表,然后让该类的多个实例同时读取它(并枚举它)而不进行任何锁定。

在本文中 http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx MS是这样描述线程安全问题的:

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A List 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.

的 “通过集合进行枚举本质上不是线程安全的过程。” 我担心的是声明。

这是否意味着只要您不使用枚举,它就只对读者场景是线程安全的?

或者它对我的场景安全吗?


感谢您的回答。 如果有或没有 AsReadOnly 都能正常工作,为什么我还需要使用 AsReadOnly?

最佳答案

它们的意思是,如果您枚举一个集合而另一个线程(或您自己的线程)更改它,您就会遇到问题。

只要您根本不更改集合,并且只要您不跨线程共享 IEnumerator,就不会有任何问题。

关于c# - C# List<T> 的线程安全给读者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2822982/

相关文章:

r - 将一个列表映射到另一个列表

python-3.x - 如何将两个嵌套列表附加到Python中的单个嵌套列表中

java - 最终不可修改的集合线程安全吗?

swift - 如何线程安全地归档一组自定义对象?

c# - 预测两个 double 之和

c# - ADO.NET Entity Framework : Converting String to Int in Where/OrderBY

arrays - List.Sort IComparer 性能

c# - 如何运行 jQuery 使用 HttpHandler

c# - .Net Web 服务器之间的除法舍入/小数差异

java - 在Java中使用 "final"参数线程安全