【发布时间】:2021-06-08 02:07:32
【问题描述】:
我注意到在讨论不可变集合的问题中(例如What is the preferred method of updating a reference to an immutable object?)
建议使用Interlocked(或更好的ImmutableInterlocked)。原因似乎是 CAS,因为在大多数情况下,不可变集合会根据其先前的值进行更新。但是,假设我有一些包装了一个不可变集合的类,我希望它可以同时访问,并且新值不依赖于旧值,使用Interlocked 仍然是首选吗?换句话说,我有什么理由更喜欢这个:
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);
}
}
在此:
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;
}
}
【问题讨论】:
标签: c# concurrency immutability volatile interlocked