tags:

views:

84

answers:

1

What is the minimum time you need to Thread.Sleep( ) to ensure DateTime.Now differs ?

Given a DateTime has a Ticks property you could argue the following would suffice:

Thread.Sleep(TimeSpan.FromTicks(1));

which would be fine but does this guarantee subsequent calls to DateTime.Now are not equal?

UPDATE: Appears DateTime precision is hardware dependent so instead I am going to use the following method:

public static void SleepUntilDateTimeChanges()
    {
        DateTime now = DateTime.Now;
        while(now == DateTime.Now)
            Thread.Sleep(TimeSpan.FromMilliseconds(1));
    }
+2  A: 

A "tick" is 100 nanoseconds. Or 1/10,000th of a millisecond. Thread.Sleep operates on milliseconds. While it's true it accepts a TimeSpan, a value less than a millisecond will be ignored (i.e. same as zero). According to @wal the resolution of only 10 milliseconds can be guaranteed. If you wait that amount you should get unique DateTime instances.

See also this explanation by Eric Lippert which sheds some more light on DateTime precision.

Kirk Woll
Thanks for the link. Someone posted:"From MSDN you'll find that DateTime.Now has an approximate resolution of 10 milliseconds on all NT operating systems."so I am going to use the method posted in my Update (above)
wal
Kirk, can you edit your answer 'if you wait a full millisecond' as that may not turn out to be true given the info on the link you sent. I can then accept your answer. :)
wal
@wal, thanks, good to know. Answer updated.
Kirk Woll
Kirk, Sorry. The resolution of 10 ms cannot be guaranteed, it is hardware specific (according to that link). Cheers.
wal
See also http://blogs.msdn.com/b/ericlippert/archive/2010/04/08/precision-and-accuracy-of-datetime.aspx
Eric Lippert