Created
September 26, 2015 23:02
-
-
Save anonymous/594aef41ba7920fa0f6d to your computer and use it in GitHub Desktop.
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
public class CurrentTimeGetter | |
{ | |
private volatile Holder _holder; | |
public string GetCurrentTimeAsString() | |
{ | |
DateTime now = DateTime.UtcNow; | |
Holder currentHolder = _holder; | |
if (currentHolder == null || Math.Abs(now.Ticks - currentHolder.TimeValue.Ticks) > TimeSpan.TicksPerSecond) | |
{ | |
// value didn't exist or was out of date | |
currentHolder = new Holder() | |
{ | |
TimeValue = now, | |
TimeValueAsString = now.ToString() // or whatever format | |
}; | |
_holder = currentHolder; | |
} | |
return currentHolder.TimeValueAsString; | |
} | |
private sealed class Holder | |
{ | |
internal DateTime TimeValue; | |
internal string TimeValueAsString; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment