38 lines
No EOL
1.1 KiB
C#
38 lines
No EOL
1.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace JD.Core
|
|
{
|
|
/// <summary>
|
|
/// A simple implementation of a cache that will compute a variation only once.
|
|
/// </summary>
|
|
public class Cache<TKey, TValue>
|
|
{
|
|
private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
|
|
|
|
/// <summary>
|
|
/// Looks into its cache first, when the result is not present uses the <paramref name="computeResult"/> to compute the result.
|
|
/// </summary>
|
|
public TValue GetOrCompute(TKey key, Func<TKey, TValue> 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);
|
|
}
|
|
}
|
|
}
|
|
} |