How to cache method results in .Net
Using webmethods开发者_如何学JAVA, caching the results is pretty straight forward using "CacheDuration" attribute. Is there a similar "easy" way to cache non-webmethod outputs (or static methods) based on the parameters?
I would appreciate any help. Thanks in advance!
The simplest way to implement a cache is to use a Dictionary or similar data structure within your class to hold results in memory for successive calls.
public class CachedDatastore
{
private Dictionary<string, object> cache = new Dictionary<string, object>();
public void FindById(string id)
{
if (!cache.ContainsKey(id))
{
var data = GetDataFromDatabase(id);
cache[id] = data;
}
return cache[id];
}
}
This is just a basic example if you want to try to implement something on your own. It does not support cache "eviction" or re-loading data at any time. If you need more advanced features, I'd recommend looking around in the .NET framework for cache classes or other 3rd party libraries.
This question looks similar to: Is there anyway to cache function/method in C#
The right term for what you want is memoization. Wikipedia gives more details on this subjects. Unfortunately there is no reference to a C# library supporting it. There are various ways to implement it yourself. But since I am not experienced in C# I can not give any more detail. Some techniques that could be used: AOP, Annotations, Proxies.
精彩评论