Search code examples
c#.netazurecachingazure-cloud-services

Duplicate keys while adding data to cache


I'm using the following code to add data to my cache:

public void Add(string key, object item, int duration)
    {
        if (DataCacheHelper.DataCache.Get(key) == null)
        {
            if (duration > 0)
            {
                DataCacheHelper.DataCache.Add(key, item, new TimeSpan(0, 0, 0, 0, duration));
            }
            else
            {
                DataCacheHelper.DataCache.Add(key, item);
            }
        }
        else
        {
            Update(key, item);
        }
    }

Notice how I have the 'if' statement before I add the data to either add it or update.

Still with this code I'm still getting the following error: enter image description here

Does anyone know what I'm missing in all this?

The program is running on an Azure Cloud service with 2 instances. Not sure if that has anything to do with it.

Thanks.


Solution

  • You can just use DataCache.Put to add or replace the cached object:

    If the object is not present when this method is called, it will be added to the cache. If the object is already present, it will be replaced. (src)

    This is the resulting method:

    public void Add(string key, object item, int duration)
    {
        if (duration > 0)
        {
             DataCacheHelper.DataCache.Put(key, item, new TimeSpan(0, 0, 0, 0, duration));
        }
        else
        {
             DataCacheHelper.DataCache.Put(key, item);
        }
    }