How to deal with costly building operations using MemoryCache?
We solved this issue by combining Lazy<T> with AddOrGetExisting to avoid a need for a lock object completely. Here is a sample code (which uses infinite expiration): public T GetFromCache<T>(string key, Func<T> valueFactory) { var newValue = new Lazy<T>(valueFactory); // the line belows returns existing item or adds the new value if it doesn’t exist … Read more