开发者

C#: Do I have to make ArrayList synchronized if multiple threads only read it

I'm using s开发者_StackOverflowtatic 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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜