I noticed that in questions discussing immutable collections (e.g. What is the preferred method of updating a reference to an immutable object?)
it was advised to use Interlocked
(or better ImmutableInterlocked
). The reason for this seems to be for CAS, since in most cases an immutable collection is updated based off of its previous value. However, suppose I have some class wrapping an immutable collection which I expect to be accessed concurrently and where new values do not depend on old values, would using Interlocked
still be preferred? In other words, is there any reason for me to prefer this:
public class Data {
private ImmutableList<string> values;
public ImmutableList<string> Read() {
return Interlocked.CompareExchange(ref values, null, null);
}
public void Write(IEnumerable<string> update) {
//some arbitrary transformation that doesn't use values at all
var newValues = update.Select(x => x + "-update").ToImmutableList();
Interlocked.Exchange(ref values, newValues);
}
}
over this:
public class Data {
private volatile ImmutableList<string> values;
public ImmutableList<string> Read() {
return values;
}
public void Write(IEnumerable<string> update) {
//some arbitrary transformation that doesn't use values at all
var newValues = update.Select(x => x + "-update").ToImmutableList();
values = newValues;
}
}