C#:如果多个线程只读取ArrayList,我是否必须使其同步
我在类中使用静态 ArrayList 来存储有关不可更新数据库字段的信息。我计划在构造函数中初始化它一次(初始化方法调用由构造函数中的锁保护)。之后多个线程检查 arraylist 是否包含字段。我是否必须以任何方式控制此读取访问权限?例如通过调用 ArrayList.Synchronized。
I'm using static ArrayList in a class to store information about non-updatable database fields. I'm planing to initialize it in constructor once (init method call guarded by lock in constructor). After that multiple threads check if arraylist Contains a field. Do I have to control this read access in any way? For example by calling ArrayList.Synchronized.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
否(并且您在创建它时不需要这样做,只要您在
static
构造函数中执行即可,它具有隐式多线程锁 - 如果您无法做到这一点,您可能会想要锁定)。如果您最终需要 R/W 访问,则可以使用 ReaderWriterLockSlim 来控制访问。No (and you shouldnt need to when creating it either as long as you do it in the
static
constructor, which has an implicit multithread lock - if you're not in a position to do that, you probably will want to lock). There's a ReaderWriterLockSlim if you can use to control access if you do end up needing to to R/W access though.不需要。仅当您要更改状态的有状态对象时才需要同步。
No. Synchronisation is only required for stateful objects where your are going to change the state.
不,只要你在读书,你就可以享受它。
No, as long as you're reading you can just have at it.
否,但请考虑将其包装在
ReadOnlyCollection
确保没有任何线程可以修改它。编辑:但是,要执行此操作,您需要将列表设为
List
而不是ArrayList
。No, but consider wrapping it in a
ReadOnlyCollection
to make sure none of the threads can modify it.Edit: However, to do this, you'd need to make the list a
List<T>
rather than anArrayList
.对于列表的初始创建,您可以考虑使用静态构造函数。仅在第一次引用该类型时调用一次。
For the initial creation of your List you could consider using a static constructor. This will only be called once on the first reference to the type.