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:
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:
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<int> GetRecordCount() { int recordCount = 0; IQueryable<Result> query = _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<int> GetRecordCount() { var cacheKey = "_cust_count"; int recordCount = 0; // Look for cache key. if (!_cache.TryGetValue(cacheKey, out recordCount)) { // Key not in cache, so get data. IQueryable<Result> query = _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(cacheKey, recordCount, cacheEntryOptions); } return recordCount; }