1

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.

2
  • Caching has nothing to do with being asynchronous, but using a static Dictionary instance as a cache is a bad idea either way. msdn.microsoft.com/en-us/library/… Commented Feb 14, 2014 at 7:15
  • I know it's not a good idea. That's why I would like to stop my sins right now :-) For the second part of my question. Is there any gain of caching the values wrapped in Task ? Commented Feb 14, 2014 at 7:25

1 Answer 1

1

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.