Can you use ConcurrentDictionary to match one to many?

I have a mapping in which each key can have several related values. I thought ConcurrentDictionary might help me more easily copy this map for use in a multi-threaded environment, but the methods seem to be built around a single value. I see that AddOrUpdate () allows me to change the value if it already exists, but it does not guarantee atomicity for this operation, so it seems pointless? Does anyone have a good strategy to deal with this situation?

Sorry, I think I was a little vague. I would like to have several values ​​for the key, i.e. Have an IList associated with a key. But I want to be able to add / remove values ​​from a multi-valued value in a safe way. Is it just that the AddOrUpdate + delegate method can lead to the loss of things if several calls to it were made at the same time?

+3
source share
2 answers

I thought it AddOrUpdatewas atomic, but it looks like it is not atomic with respect to the delegate. Excuse me!

Link that may help: http://blogs.msdn.com/b/pfxteam/archive/2009/11/06/9918363.aspx

+1
source

, AddOrUpdate, TryUpdate.

, . , , , , . :

public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
{
    TValue local;
    TValue local3;
    if (key == null)
    {
        throw new ArgumentNullException("key");
    }
    if (addValueFactory == null)
    {
        throw new ArgumentNullException("addValueFactory");
    }
    if (updateValueFactory == null)
    {
        throw new ArgumentNullException("updateValueFactory");
    }
    do
    {
        if (!this.TryGetValue(key, out local3))
        {
            TValue local2;
            local = addValueFactory(key);
            if (!this.TryAddInternal(key, local, false, true, out local2))
            {
                continue;
            }
            return local2;
        }
        local = updateValueFactory(key, local3);
    }
    while (!this.TryUpdate(key, local, local3));
    return local;
}

, factory , , . factory. ?

0

Source: https://habr.com/ru/post/1756031/


All Articles