2023-02-08 14:15:35 +01:00
|
|
|
namespace CommonHelpers
|
|
|
|
|
{
|
2023-02-11 13:37:17 +01:00
|
|
|
public struct TimedValue<T> where T : struct
|
2023-02-08 14:15:35 +01:00
|
|
|
{
|
|
|
|
|
public T Value { get; }
|
|
|
|
|
public DateTime ExpiryDate { get; }
|
|
|
|
|
|
|
|
|
|
public bool Valid
|
|
|
|
|
{
|
|
|
|
|
get => !Expired;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool Expired
|
|
|
|
|
{
|
|
|
|
|
get => ExpiryDate < DateTime.UtcNow;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public TimedValue(T value, TimeSpan ts)
|
|
|
|
|
{
|
|
|
|
|
this.Value = value;
|
|
|
|
|
this.ExpiryDate = DateTime.UtcNow.Add(ts);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public TimedValue(T value, int timeoutMs)
|
|
|
|
|
: this(value, TimeSpan.FromMilliseconds(timeoutMs))
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public bool TryGetValue(out T value)
|
|
|
|
|
{
|
|
|
|
|
value = this.Value;
|
|
|
|
|
return Valid;
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-11 13:37:17 +01:00
|
|
|
public T? GetValue()
|
|
|
|
|
{
|
|
|
|
|
return Valid ? Value : null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public T GetValueOrDefault(T defaultValue)
|
|
|
|
|
{
|
|
|
|
|
return Valid ? Value : defaultValue;
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-08 14:15:35 +01:00
|
|
|
public static implicit operator T?(TimedValue<T> tv)
|
|
|
|
|
{
|
2023-02-11 13:37:17 +01:00
|
|
|
return tv.GetValue();
|
2023-02-08 14:15:35 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|