Cache an object for a specified duration of time.

The example will cache the sorted list of domain controllers (involving several expensive ADSI calls) for 10 hrs.
Code Snippet

public class Cached<T>


    private TimeSpan duration;

    private DateTime expiration;

    private T cachedResponse;

    private Func<T> loadDelegate;


    public T Value




            if (DateTime.Now > expiration)


                cachedResponse = loadDelegate();

                expiration = DateTime.Now.Add(duration);


            return cachedResponse;




    public Cached(TimeSpan CacheDuration, Func<T> LoadDelegate)


        if (duration < TimeSpan.Zero)

            throw new ArgumentOutOfRangeException("Cache duration cannot be negative");


        duration = CacheDuration;

        loadDelegate = LoadDelegate;


        // start with expired cache (also, starting with expired/null data instead enables us to lazy load the data)

        expiration = DateTime.Now.AddMinutes(-1);



    public static explicit operator T(Cached<T> o) { return o.Value; }

    //public static implicit operator T(SimpleCache<T> o) { return o.Value; }

} // class Cached<T>


// Keep the list of DC's cached for a reasonably long period of time...
//   the forest lookups required to obtain this info is expensive

private static Cached<IEnumerable<string>> OrderedServerList = new Cached <IEnumerable<string>>(
        () => DomainControllers().ToList()

Created 2012-03-07
comments powered by Disqus