sharp-chat/SharpChatCommon/Config/CachedValue.cs

49 lines
1.6 KiB
C#
Raw Permalink Normal View History

using System;
namespace SharpChat.Config {
public class CachedValue<T> {
private IConfig Config { get; }
private string Name { get; }
private TimeSpan Lifetime { get; }
2024-05-10 19:18:55 +00:00
private T? Fallback { get; }
private object ConfigAccess { get; } = new();
2024-05-10 19:18:55 +00:00
private object? CurrentValue { get; set; }
private DateTimeOffset LastRead { get; set; }
2024-05-10 19:18:55 +00:00
public T? Value {
get {
lock(ConfigAccess) { // this lock doesn't really make sense since it doesn't affect other config calls
DateTimeOffset now = DateTimeOffset.Now;
if((now - LastRead) >= Lifetime) {
LastRead = now;
CurrentValue = Config.ReadValue(Name, Fallback);
Logger.Debug($"Read {Name} ({CurrentValue})");
}
}
2024-05-10 19:18:55 +00:00
return (T?)CurrentValue;
}
}
2024-05-10 19:18:55 +00:00
public static implicit operator T?(CachedValue<T> val) => val.Value;
2024-05-10 19:18:55 +00:00
public CachedValue(IConfig config, string name, TimeSpan lifetime, T? fallback) {
if(string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Name cannot be empty.", nameof(name));
Config = config;
Name = name;
Lifetime = lifetime;
Fallback = fallback;
}
public void Refresh() {
LastRead = DateTimeOffset.MinValue;
}
public override string ToString() {
2024-05-10 19:18:55 +00:00
return Value?.ToString() ?? string.Empty;
}
}
}