How should I implement the Func in AddOrUpdate() in this object: ConcurrentDictionary<int, List<MyObject>>

StackOverflow https://stackoverflow.com/questions/12946377

Pergunta

How do I implement AddorUpdate in ConcurrentDictionary so that I can correctly update the value, if that value is a collection?

My concern is that since TValue is a reference type I might run into the situation where I call TValue multiple times in a race condition. I would test this myself, but my syntax is wrong so I can't proceed further.

What must I change to make this work?

   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...
           );
        }
    }
Foi útil?

Solução

The purpose of AddOrUpdate() is to replace any existing value with a new value.

Since you only need to get the existing value (in order to then modify it), you want GetOrAdd():

this.GetOrAdd(detail.HierarchyDepth, new ConcurrentBag<TrustRelationshipDetail>())
        .Add(detail);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top