ASP.NET MVC 5 thread safe cache?

Viewed 36

Help guys, have products list with singleton class with caching and these 2 methods:

private readonly static object Lock = new object();

private List<BaseItem> GetProducts()
{
    lock (Lock)
    {
        List<BaseItem> products = (List<BaseItem>)HttpRuntime.Cache.Get("Products");

        if (products == null)
        {
            products = DBManager.inst.GetProducts();
            HttpRuntime.Cache.Insert("Products", products, null,
            DateTime.MaxValue, TimeSpan.FromHours(48));
        }

        return products;
    }
}

And GetProduct:

public BaseItem GetProduct(int ArticulID)
{
    lock (Lock)
    {
        return GetProducts().Where(x => x.Articul == ArticulID).FirstOrDefault();
    }
}

Is this the right solution - is it thread safe?

1 Answers

I would use MemoryCache. It is thread safe and you don't need the lock anymore. Install it using the Nuget package. More sense would make to add each BaseItem individually into the cache with a unique key, but this is up to you.

    MemoryCache memChInst = new MemoryCache("Products");

    List<BaseItem> testList = new List<BaseItem>() { new BaseItem() { Id = 1 }, new BaseItem { Id = 3 } };

    List<BaseItem> GetProducts()
    {          
        var  retData =  (List<BaseItem >)memChInst.AddOrGetExisting("Key1", testList, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(48) });
        return retData ?? testList;
    }

    var xx =GetProducts();
    var yy = GetProducts();
    var zz = GetProducts();
Related