Skip to content

Instantly share code, notes, and snippets.

Created September 26, 2015 23:02
Show Gist options
  • Save anonymous/594aef41ba7920fa0f6d to your computer and use it in GitHub Desktop.
Save anonymous/594aef41ba7920fa0f6d to your computer and use it in GitHub Desktop.
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