views:

61

answers:

1

Using webmethods, 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!

A: 

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.

Andy White
Hello, Andy. Thanks for the reply, but I was looking for a more easier way to implement across many different methods without having to do them individually. For example, annotating a static method of some attribute which enables caching of that method, similar to WebMethod's "CacheDuration". Is there another easy way that I am missing? If not, is there an example of attribute programming that can accomplish this?Thanks in advance.
SP