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:

c# httpclient The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

 If we get this error while trying to get http reponse using HttpClient object, it could mean that certificate validation fails for the remo...