下面是一些使用Thread.Sleep暂停执行的简单代码,以及使用Stopwatch.ElapsedMilliseconds来查找线程实际睡眠的时间。
Dim sw As New Stopwatch()
Dim elapsed_ms As Integer = 0
sw.Start()
While True
Threading.Thread.Sleep(10)
elapsed_ms = CInt(sw.ElapsedMilliseconds)
Debug.WriteLine("Elapsed: " & elapsed_ms & " ms")
sw.Restart()
End While
我的问题是:偶尔,调试打印说0 ms已经过去了。这怎么可能?我知道Thread.Sleep(10)不准确,并且通常睡眠时间超过10毫秒,但我认为它保证至少睡10毫秒。 / p>
答案 0 :(得分:0)
我个人尽量避免在我的代码中使用Thread.Sleep
,原因有多种,但您看到的不正常之处就是其中之一。
因此,我不会调用Thread.Sleep
而是计算将来的超时,无论你应该为什么增加睡眠,然后使用不执行任何操作的while
循环。因此,您的主While
循环将如下所示:
While True
Dim l_TO As Date = Now.AddMilliseconds(10)
While l_TO > Now
'Do Nothing,
'Sometimes I will put a Thread.Sleep call in here but that's usually if the amount of time being waited is more than seconds.
'Mainly because a loop of this nature will chew up more processing power than you would expect.
Thread.Sleep(1) 'Probably not need because of the short time that you are forcing the program to wait.
End While
elapsed_ms = CInt(sw.ElapsedMilliseconds)
Debug.WriteLine("Elapsed: " & elapsed_ms & " ms")
sw.Restart()
End While
我知道这并不能解释为什么你会看到Thread.Sleep
的奇怪行为但我认为值得一提的是Thread.Sleep
有很多缺点,可以很容易地避免。