c# Immutability 创建全局存储

c# Immutability creating a global store

对于我的项目,我正在尝试创建一个全局存储来服务于这样的可变状态:

  // Immutable program state
  sealed public class State : IEquatable<State> {
    public State(ClientsConnections clientsConnections, ImmutableList<string> ids) {
      this.ClientsConnections = clientsConnections;
      this.Ids = ids;
    }

    public readonly ClientsConnections ClientsConnections; // ClientsConnections is immutable
    public readonly ImmutableList<string> Ids; // also immutable

    public override int GetHashCode() => HashCode.Combine(AgentsConnections.GetHashCode(), Ids.GetHashCode());
    public override bool Equals(object obj) { var o = obj as State; return o is null ? false : ClientsConnections.Equals(o.ClientsConnections) && Ids.Equals(Ids); }
    public bool Equals(State o) => object.Equals(this, o); 
    public static bool operator ==(State o1, State o2) => object.Equals(o1, o2); 
    public static bool operator !=(State o1, State o2) => !object.Equals(o1, o2);
  }

  // Store is a mutable singleton
  sealed public class Store {
    readonly object stateLock = new object();

    public Store() => this.State = new State(new ClientsConnections(), ImmutableList<string>.Empty);

    public State State { get; private set; }
    public void SetState(Func<State, State> f) { lock (stateLock) State = f(State); }
  }

然后我像这样在代码中使用它:

Thread1 - f1() { 
  var currState=Store.State; 
  log(currState.ids);
}

Thread2 - f2() { 
  Store.SetState(currState => {
    var newids = currState.Ids.Add("hello");
    return new State(currState.ClientsConnections, newids);
  });
}

问题:

  1. 这段代码线程安全吗?特别是我需要锁定 Store.State getter 吗?我的推理是因为 getter 执行原子分配按值复制状态引用然后我不需要在这里锁定它?

  2. 我可以I/should在这里使用 ImmutableInterlocked 吗?

Is this code thread safe ? in particular do I need to lock the Store.State getter ? my reasoning is since the getter does an atomic assignment copying the state reference by value then I do not need to lock it here ?

只要您对陈旧数据感到满意,是的,它会正常工作。

Can I/should I use ImmutableInterlocked here ?

是的,我认为你应该这样做(但你应该分析以确认它是否真的提供了好处)。 ImmutableInterlocked.Update 是我的建议。