I have a heavily threaded application with a ReadOnlyCollection as follows:
internal static ReadOnlyCollection<DistributorBackpressure44> DistributorBackpressure44Cache
{
get
{
return _distributorBackpressure44;
}
set
{
_distributorBackpressure44 = value;
}
}
I have one place in the app where this collection is replaced (always on a separate thread) and it looks like this:
CicApplication.DistributorBackpressure44Cache = new ReadOnlyCollection<DistributorBackpressure44>(someQueryResults.ToList());
I have many places in the code where this collection is accessed, usually via Linq queries, in many different threads. The code often looks something like this:
foreach (DistributorBackpressure44 distributorBackpressure44 in CicApplication.DistributorBackpressure44Cache.Where(row => row.Coater == coater && row.CoaterTime >= targetTime).ToList())
{
...
...
}
I assume what I’m doing is thread-safe, without the need to do any locking? What I’m not sure about is what happens with the query above if it occurs at the exact same time the collection is getting replaced in a different thread?
Reference assignments are atomic, so yes, it is thread safe. But only as long as you don’t rely on the data to be ready to be read exactly the moment after it is written. This is because of caching, you might want to throw in a
volatileto prevent that.See also reference assignment is atomic so why is Interlocked.Exchange(ref Object, Object) needed?.