From afb55e6b16ecea04f0a89aa1b67a4bb099745c47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20Trzci=C5=84ski?= Date: Wed, 8 Feb 2023 14:15:35 +0100 Subject: [PATCH] CommonHelpers: Add `TimedValue` helper --- CommonHelpers/TimedValue.cs | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 CommonHelpers/TimedValue.cs diff --git a/CommonHelpers/TimedValue.cs b/CommonHelpers/TimedValue.cs new file mode 100644 index 0000000..4d27b23 --- /dev/null +++ b/CommonHelpers/TimedValue.cs @@ -0,0 +1,40 @@ +namespace CommonHelpers +{ + public class TimedValue where T : struct + { + 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; + } + + public static implicit operator T?(TimedValue tv) + { + return tv.Valid ? tv.Value : null; + } + } +}