Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic implementation of System.Runtime.Caching.MemoryCache

Is there any generic alternative / implementation for MemoryCache?

I know that a MemoryCache uses a Hashtable under the hood, so all it would take is to transition into using a Dictionary<,>, which is the generic version of a Hashtable.

This would provide type safety and provide performance benefits as no boxing/unboxing.

EDIT: Another thing I'm interested in is having a different key type. The default is a System.String.

like image 741
caesay Avatar asked Jun 13 '12 15:06

caesay


2 Answers

Is there any generic alternative / implementation for MemoryCache?

Not in the base class library. You'd have to roll your own, though I, personally, would just make a wrapper around MemoryCache that provides the API you wish.

This would provide type safety and provide performance benefits as no boxing/unboxing

The type safety can be handled fairly easily in a wrapper class. The boxing/unboxing would only be an issue if you were storing value types (not classes), and even then, would likely be minimal, as it's unlikely that you're pushing and pulling from cache often enough to have this be a true performance issue.

As for type safety and usability, I've actually written my own methods to wrap the MemoryCache item's calls in a generic method, which allows a bit nicer usage from an API standpoint. This is very easy - typically just requires a method like:

public T GetItem<T>(string key) where T : class
{
    return memoryCache[key] as T;
}

Similarly, you can make a method to set values the same way.

EDIT: Another thing I'm interested in is having a different key type. The default is a System.String.

This is not supported directly with MemoryCache, so it would require a fair bit of work to make your own key generation. One option would be to make a type safe wrapper which also provided a Func<T, string> to generate a string key based off your value - which would allow you to generate a cache entry for any type T. You'd have to be careful, of course, to include all data in the string that you wanted as part of your comparison, however.

like image 169
Reed Copsey Avatar answered Oct 10 '22 19:10

Reed Copsey


I wrote mine, FWIW:

https://github.com/ysharplanguage/GenericMemoryCache#readme (link dead)

There is a fork of the original code here:

https://github.com/caesay/GenericMemoryCache

like image 1
YSharp Avatar answered Oct 10 '22 18:10

YSharp