Created
March 15, 2022 01:12
-
-
Save wallstop/96c5d3cd0d6045b0571de6448f052369 to your computer and use it in GitHub Desktop.
TimedCache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Core.DataStructure | |
{ | |
using System; | |
using Helper; | |
using Random; | |
using UnityEngine; | |
public sealed class TimedCache<T> | |
{ | |
public T Value | |
{ | |
get | |
{ | |
if (!_lastRead.HasValue || UnityHelpers.HasEnoughTimePassed(_lastRead.Value, _cacheTtl)) | |
{ | |
_value = _valueProducer(); | |
_lastRead = Time.time; | |
if (_useJitter) | |
{ | |
_lastRead += SystemRandom.Instance.NextFloat(-0.1f, 0.1f); | |
} | |
} | |
return _value; | |
} | |
} | |
private readonly Func<T> _valueProducer; | |
private readonly float _cacheTtl; | |
private readonly bool _useJitter; | |
private float? _lastRead; | |
private T _value; | |
public TimedCache(Func<T> valueProducer, float cacheTtl, bool useJitter = false) | |
{ | |
_valueProducer = valueProducer ?? throw new ArgumentNullException(nameof(valueProducer)); | |
if (cacheTtl < 0) | |
{ | |
throw new ArgumentException(nameof(cacheTtl)); | |
} | |
_cacheTtl = cacheTtl; | |
_useJitter = useJitter; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment