using System; using System.Collections.Generic; namespace JD.Core { /// /// A simple implementation of a cache that will compute a variation only once. /// public class Cache { private readonly Dictionary _dictionary = new Dictionary(); /// /// Looks into its cache first, when the result is not present uses the to compute the result. /// public TValue GetOrCompute(TKey key, Func computeResult) { TValue result; if (!TryGetValue(key, out result)) { result = computeResult(key); lock (_dictionary) { _dictionary[key] = result; } } return result; } private bool TryGetValue(TKey key, out TValue result) { lock (_dictionary) { return _dictionary.TryGetValue(key, out result); } } } }