开发者

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

What is the minimum time you need to Thread.Sl开发者_Python百科eep( ) 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));
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜