Wednesday, February 19, 2020

Dot net core lazy cache

Here is how we can cache results in async methods using dot net core framework.

Lets say we have an entity in EF Core data context called Customer and we have an async method to get record count from customer table like so:


public async Task<intGetRecordCount()
        {
            int recordCount = 0;
 
            IQueryable<Resultquery = _dataContext.Customer;
            
            recordCount = await query.CountAsync();
 
            return recordCount;
        }



Now, since this query is quite slow, and we would like to make the application more responsive, we might want to cache the record count for say three minutes. Here is the simple way:

public async Task<intGetRecordCount()
        {
            var cacheKey = "_cust_count";
 
            int recordCount = 0;
 
            // Look for cache key.
            if (!_cache.TryGetValue(cacheKeyout recordCount))
            {
                // Key not in cache, so get data.
                IQueryable<Resultquery = _dataContext.Customer;
 
                recordCount = await query.CountAsync();
 
                // Set cache options.
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    // Keep in cache for this time, reset time if accessed.
                    .SetAbsoluteExpiration(TimeSpan.FromMinutes(3));
 
                // Save data in cache.
                _cache.Set(cacheKeyrecordCountcacheEntryOptions);
            }
 
            return recordCount;
        }


No comments:

SSL Error - The connection for this site is not secure

 After cloning a git repo of dot net framework website and trying to run it all I could see was this error Turns out the fix was to simply e...