MSDN vaguely mentions:
A ReadOnlyCollection<(Of <(T>)>) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can 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.
Would the following public static collection be safe for multiple threads to iterate over? If not, is there something built into .NET that is safe? Should I just drop the ReadOnlyCollection
and create a new copy of a private collection for each access of a SomeStrings property getter? I understand that there could be a deadlock issue if multiple threads tried to lock on the public collection, but this is an internal library, and I can't see why we would ever want to.
public static class WellKnownStrings {
public static readonly ICollection<string> SomeStrings;
static WellKnownStrings()
{
Collection<string> someStrings = new Collection<string>();
someStrings.Add("string1");
someStrings.Add("string2");
SomeStrings = new ReadOnlyCollection<string>(someStrings);
}
}