Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using attributes to cache a method's return results in C#

In webmethods, it is very simple to implement caching by annotating [WebMethod(CacheDuration...] attribute. Can we create something similar for non-webmethods, such as Static methods?

Any help/tip is appreciated.

like image 967
SP. Avatar asked May 05 '10 02:05

SP.


3 Answers

There is no built in feature for achieving exactly what you want. You should use Httpruntime.Cache.

It's not a built in feature but you may achieve something like that using aspect oriented programming (AOP). Caching information using aspects.

In case you're interested Spring.NET provides AOP

like image 96
Claudio Redi Avatar answered Oct 01 '22 18:10

Claudio Redi


Check this simple implementation of an attribute for caching using Post Sharp.

like image 42
Fernando Avatar answered Oct 01 '22 19:10

Fernando


If you can't use AOP to get the job done you could try using this little class I put together.

public MyClass CachedInstance
{
    get { return _cachedInstance.Value; }
}
private static readonly Cached<MyClass> _cachedInstance = new Cached<MyClass>(() => new MyClass(), TimeSpan.FromMinutes(15));

public sealed class Cached<T>
{
    private readonly Func<T> _createValue;
    private readonly TimeSpan _cacheFor;
    private DateTime _createdAt;
    private T _value;


    public T Value
    {
        get
        {
            if (_createdAt == DateTime.MinValue || DateTime.Now - _createdAt > _cacheFor)
            {
                lock (this)
                {
                    if (_createdAt == DateTime.MinValue || DateTime.Now - _createdAt > _cacheFor)
                    {
                        _value = _createValue();
                        _createdAt = DateTime.Now;
                    }
                }
            }
            return _value;
        }
    }


    public Cached(Func<T> createValue, TimeSpan cacheFor)
    {
        if (createValue == null)
        {
            throw new ArgumentNullException("createValue");
        }
        _createValue = createValue;
        _cacheFor = cacheFor;
    }
}
like image 28
ChaosPandion Avatar answered Oct 01 '22 20:10

ChaosPandion