Skip to content

Commit

Permalink
CommonHelpers: Add TimedValue helper
Browse files Browse the repository at this point in the history
  • Loading branch information
ayufan committed Feb 8, 2023
1 parent 759327c commit afb55e6
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions CommonHelpers/TimedValue.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
namespace CommonHelpers
{
public class TimedValue<T> 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<T> tv)
{
return tv.Valid ? tv.Value : null;
}
}
}

0 comments on commit afb55e6

Please sign in to comment.