C#:如果多个线程只读取ArrayList,我是否必须使其同步

发布于 2024-08-12 16:41:13 字数 155 浏览 3 评论 0原文

我在类中使用静态 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一枫情书 2024-08-19 16:41:13

否(并且您在创建它时不需要这样做,只要您在 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.

够钟 2024-08-19 16:41:13

不需要。仅当您要更改状态的有状态对象时才需要同步。

No. Synchronisation is only required for stateful objects where your are going to change the state.

红颜悴 2024-08-19 16:41:13

不,只要你在读书,你就可以享受它。

No, as long as you're reading you can just have at it.

楠木可依 2024-08-19 16:41:13

否,但请考虑将其包装在 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 an ArrayList.

风尘浪孓 2024-08-19 16:41:13

对于列表的初始创建,您可以考虑使用静态构造函数。仅在第一次引用该类型时调用一次。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文