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.
Not in the base class library. You’d have to roll your own, though I, personally, would just make a wrapper around
MemoryCachethat provides the API you wish.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
MemoryCacheitem’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:Similarly, you can make a method to set values the same way.
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 aFunc<T, string>to generate a string key based off your value – which would allow you to generate a cache entry for any typeT. You’d have to be careful, of course, to include all data in the string that you wanted as part of your comparison, however.