Maintaing List<T> in cache like database

337 Views Asked by At

I have a requirement where in i need to maintain a list in memory.

Eg -

list<products>

every user will run the application and add new product/update product/ remove product from the list and all the changes should be reflected on that list.

I am trying to store the list in the objectcache.

but when i run the application it creates products but the moment i run it second time the list is not in the cache. need a help.

Following is the code -

public class ProductManagement
{

    List<Productlist> _productList;
    ObjectCache cache= MemoryCache.Default;

    public int Createproduct(int id,string productname)
    {
            if (cache.Contains("Productlist"))
            {
                _productList = (List<Productlist>)cache.Get("Productlist");
            }
            else
            {
                _productList = new List<Productlist>();
            }

            Product pro = new Product();
            pro.ID = id;
            pro.ProductName = productname;

            _productList.Add(pro);

            cache.AddOrGetExisting("Productlist", _productList, DateTime.MaxValue);

            return id;
    }

    public Product GetProductbyId(int id)
    {
            if (cache.Contains("Productlist"))
            {
                _productList = (List<Productlist>)cache.Get("Productlist");
            }
            else
            {
                _productList = new List<Productlist>();
            }

            var product = _productList.Single(i => i.ID == id);
            return product;
    }

}

how i can make sure that the list is persistent even when the application is not running, can this be possible. also how to keep the cache alive and to retrieve the same cache next time.

Many thanks for help.

1

There are 1 best solutions below

10
On

Memory can be different http://en.wikipedia.org/wiki/Computer_memory. MemoryCache stores information in Process Memory, which exists only while Process exists.

If your requirement is to maintain list in process memory - your task is done, and more than you do not need to use ObjectCache cache= MemoryCache.Default; you can just keep the list as a field for ProductManagement.

If you need to keep the list between application launches - you need to do additional work to write the list to file when you close application and read it when you open application.