// Copyright Epic Games, Inc. All Rights Reserved. using System; using System.Diagnostics; namespace HordeServer.Utilities { /// /// Stores a value that expires after a given time /// /// public class LazyCachedValue where T : class { /// /// The current value /// T? _value; /// /// Generator for the new value /// readonly Func _generator; /// /// Time since the value was updated /// readonly Stopwatch _timer = Stopwatch.StartNew(); /// /// Default expiry time /// readonly TimeSpan _defaultMaxAge; /// /// Default constructor /// public LazyCachedValue(Func generator, TimeSpan maxAge) { _generator = generator; _defaultMaxAge = maxAge; } /// /// Sets the new value /// /// The value to store public void Set(T value) { _value = value; _timer.Restart(); } /// /// Tries to get the current value /// /// The cached value, if valid public T GetCached() { return GetCached(_defaultMaxAge); } /// /// Tries to get the current value /// /// The cached value, if valid public T GetCached(TimeSpan maxAge) { T? current = _value; if (current == null || _timer.Elapsed > maxAge) { current = _generator(); Set(current); } return current; } /// /// Gets the latest value, updating the cache /// /// The latest value public T GetLatest() { T newValue = _generator(); Set(newValue); return newValue; } } }