-
-
Notifications
You must be signed in to change notification settings - Fork 68
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
CommonHelpers: Add
TimedValue
helper
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |