mirror of
https://github.com/osukey/osukey.git
synced 2025-07-01 08:20:00 +09:00
Move lookup/storage/compute logic to base class (and consume in ScorePerformanceCache)
This commit is contained in:
@ -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);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user