Reputation: 1453
1
Basically, I'm trying to figure out what kind of caching mechanism is best (and easiest) for a asp.net MVC5 solution. In previous synchronious solutions, I have used a static dictionary,and the lock keyword when accessing it.
private static Dictionary<string, object> _cache;
private static object _cacheLocker = new object();
private object GetFromCache(string key)
{
return _cache[key];
}
private void AddToCache(string key, object value)
{
lock (_cacheLocker)
{
_cache.Add(key, value);
}
}
But I think there must be a more elegant way of doing this in an async world.
2
What should I cache in an async method? Only the values or the values wrapped inside a Task
Thank you.
Upvotes: 1
Views: 590
Reputation: 36
I'm using this method for my caching.
protected ObjectCache cache = MemoryCache.Default;
protected T GetCacheOrExecute<T>(string key, Func<T> addToCacheFunction)
{
if (cache.Contains(key))
{
return (T)cache.Get(key);
}
else
{
T retValue = default(T);
if (null != addToCacheFunction)
{
retValue = addToCacheFunction();
var cachItem = new CacheItem(key, retValue);
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30); //The cache time out
cache.Add(cachItem, policy);
}
return retValue;
}
}
And I call it like this:
public async Task<IEnumerable<User>> GetAllUsersAsync()
{
return await base.GetCacheOrExecute("users", doGetAllUsersAsync); //
}
private async Task<IEnumerable<User>> doGetAllUsersAsync() {
//more code...
}
Hope this helps...
Upvotes: 1