Can(should?) Lazy<T> be used as a caching technique?

I'd like to use .NET's Lazy<T> class to implement thread safe caching. Suppose we had the following setup:

class Foo
    Lazy<string> cachedAttribute;


    string initCache()
        string returnVal = "";
        return returnVal;

    public String CachedAttr
            return cachedAttribute.Value;

    void invalidateCache()
        cachedAttribute = new Lazy<string>(initCache, true);

My questions are:

  1. Would this work at all?
  2. How would the locking have to work?

I feel like I'm missing a lock somewhere near the invalidateCache, but for the life of me I can't figure out what it is.

I'm sure there's a problem with this somewhere, I just haven't figured out where.


Ok, well it looks like I was right, there were things I hadn't thought about. If a thread sees an outdated cache it'd be a very bad thing, so it looks like "Lazy" is not safe enough. The Property is accessed a lot though, so I was engaging in pre-mature optimization in hopes that I could learn something and have a pattern to use in the future for thread-safe caching. I'll keep working on it.

P.S.: I decided to make the object thread-un-safe and have access to the object be carefully controlled instead.


Well, it's not thread-safe in that one thread could still see the old value after another thread sees the new value after invalidation - because the first thread could have not seen the change to cachedAttribute. In theory, that situation could perpetuate forever, although it's pretty unlikely :)

Using Lazy<T> as a cache of unchanging values seems like a better idea to me - more in line with how it was intended - but if you can cope with the possibility of using an old "invalidated" value for an arbitrarily long period in another thread, I think this would be okay.

Need Your Help

FadeIn and fadeOut DIV border for 3 seconds only

javascript jquery

How do I keep a fadeIn and fadeOut active for 3 seconds and clear the effect?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.