Home > Back-end >  Check data exist in cache or not
Check data exist in cache or not

Time:12-18

In below function I want to cache a data and store into cache memory, from the service I am getting data .

I dont know how to check whether data is exist in cache or not , if suppose data is exist in cache then I dont want to call webservice just display data which is exist in cache memory.

    public string EmployeeNames
    {
        get
        {
            var employeenames = System.Runtime.Caching.MemoryCache.Default["EmployeeNames"];
            
            // getting data from web service one bye one and storing into employeenames
            employeenames = AccountModel.EmployeeNames(EmployeeInfo);
            
            System.Runtime.Caching.MemoryCache.Default["EmployeeNames"] = employeenames;
            return employeenames.ToString();
        }
    }

CodePudding user response:

You could check it by using MemoryCache.Contains which determines whether a cache entry exists in the cache and in case it does, fetch it by using the Get method which will return a value whatever you have stored in the cache. if not getting it will return a null value.

var cache = System.Runtime.Caching.MemoryCache;

if (cache != null && cache.Contains("EmployeeNames"))
{
    var EmployeeNames = cache.Get("EmployeeNames");
}

More about MemoryCache.Contains - https://docs.microsoft.com/en-us/dotnet/api/system.runtime.caching.memorycache.contains?view=dotnet-plat-ext-6.0

CodePudding user response:

You can call

var employeenames = MemoryCache.Default.Get("EmployeeNames");

If the item is not present in the cache this returns null.

You can use Contains to see if an item is present:

if(MemoryCache.Default.Contains("EmployeeNames"))

but as unlikely as it is, there's a possibility that Contains will return "true" but the item won't be in the cache a moment later when you retrieve it. So I'd just Get it and see if it's null, and only use Contains to see if it's present if you don't also want to retrieve it.

  • Related