1

AddorUpdate値がコレクションである場合に値を正しく更新できるように、ConcurrentDictionaryに実装するにはどうすればよいですか?

私の懸念は、TValueは参照型であるため、競合状態でTValueを複数回呼び出す状況に遭遇する可能性があることです。これを自分でテストしますが、構文が間違っているため、先に進むことができません。

これを機能させるには何を変更する必要がありますか?

   public class TrustList :  ConcurrentDictionary<int, List<TrustRelationshipDetail>>
    {
        public void AddOrUpdateTrustDetail(TrustRelationshipDetail detail)
        {
            List<TrustRelationshipDetail> detailList = new List<TrustRelationshipDetail>();
            detailList.Add(detail);

            this.AddOrUpdate(detail.HierarchyDepth, detailList, (key, oldValue) =>   
            oldValue.Add(detail)  // <--- Compiler doesn't like this, and I think this may cause duplicates if this were to be called...
           );
        }
    }
4

1 に答える 1

2

の目的は、既存の値を新しい値AddOrUpdate()置き換えることです。

(次に変更するために)既存の値を取得するだけでよいので、次のようにしGetOrAdd()ます。

this.GetOrAdd(detail.HierarchyDepth, new ConcurrentBag<TrustRelationshipDetail>())
        .Add(detail);
于 2012-10-18T02:56:59.573 に答える