Move lookup/storage/compute logic to base class (and consume in ScorePerformanceCache)

This commit is contained in:
Dean Herbert
2020-11-06 13:50:51 +09:00
parent 517a656899
commit a2606d31c7
2 changed files with 45 additions and 23 deletions

View File

@ -2,6 +2,9 @@
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using osu.Framework.Graphics;
namespace osu.Game.Database
@ -12,6 +15,34 @@ namespace osu.Game.Database
/// </summary>
public abstract class MemoryCachingComponent<TLookup, TValue> : Component
{
protected readonly ConcurrentDictionary<TLookup, TValue> Cache = new ConcurrentDictionary<TLookup, TValue>();
private readonly ConcurrentDictionary<TLookup, TValue> cache = new ConcurrentDictionary<TLookup, TValue>();
protected virtual bool CacheNullValues => true;
/// <summary>
/// Retrieve the cached value for the given <see cref="TLookup"/>.
/// </summary>
/// <param name="lookup">The lookup to retrieve.</param>
/// <param name="token">An optional <see cref="CancellationToken"/> to cancel the operation.</param>
protected async Task<TValue> GetAsync([NotNull] TLookup lookup, CancellationToken token = default)
{
if (cache.TryGetValue(lookup, out TValue performance))
return performance;
var computed = await ComputeValueAsync(lookup, token);
if (computed != null || CacheNullValues)
cache[lookup] = computed;
return computed;
}
/// <summary>
/// Called on cache miss to compute the value for the specified lookup.
/// </summary>
/// <param name="lookup">The lookup to retrieve.</param>
/// <param name="token">An optional <see cref="CancellationToken"/> to cancel the operation.</param>
/// <returns>The computed value.</returns>
protected abstract Task<TValue> ComputeValueAsync(TLookup lookup, CancellationToken token = default);
}
}