When calling DateTime.UtcNow
multiple times in short succession, is there a way to guarantee that it will return two different times and subsequent calls will have ever-increasing values?
I'm more concerned with precision than accuracy, and this is not a timer issue (i.e., I'm not trying to time how long something takes, I just want to get 2+ "current" but unique DateTimes).
Problem Example: The following code will repeat the same Ticks value many times and only increment every 15-30ms depending on the computer's speed.
for(int i = 0; i < 1000; i++) { Console.WriteLine(DateTime.UtcNow.Ticks); }
Right now I'm doing the following, but it seems like overkill for something as simple as getting the current time to a high precision - especially the Sleep(1). Is there a better way, and does this fulfill my original question? While it's statistically unlikely I'd get duplicate values at the Ticks level, I'm not sure this guarantees my values are ever-increasing due to the possibility of my clock being reset by a time server, leap seconds, or other issues I may not be thinking of. Daylight savings shouldn't be an issue since I'm using UTC.
private static DateTime prevDateTime = DateTime.UtcNow;
private static object nowLock = new object();
public static DateTime Now()
{
lock(nowLock)
{
DateTime now = DateTime.UtcNow;
if (now <= prevDateTime)
{
System.Threading.Thread.Sleep(1);
now = DateTime.UtcNow;
}
prevDateTime = now;
return now;
}
}
// then call
for(int i = 0; i < 1000; i++) { Console.WriteLine(Now()); }