VB.net不一致的线程睡眠定时器定时器、线程、睡眠、VB

2023-09-06 14:21:35 作者:對不起,此名字不存在

好了,所以我一直在玩VB.net和头脑风暴的方式来实现启动一个线程可靠每60秒reguardless多久以前的线程把做的工作。这是我的问题。鉴于以下code:

Ok so I have been playing with VB.net and brainstorming ways to accomplish launching a thread reliably every 60 seconds reguardless of how long the prior thread took to do it's work. Here is my question. Given the following code:

    Dim intTemp As Integer
    intTemp = 2
    Do While intTemp > 1
        Dim objWriter As New System.IO.StreamWriter("C:\Documents\Visual Studio 2010\Projects\Report\Report\Stream.txt", True)
        intTemp = intTemp + 1
        System.Threading.Thread.Sleep(5000)

        objWriter.Write(intTemp & " " & Date.Now & " " & Date.Now.Millisecond & vbCrLf)
        objWriter.Close()
    Loop

生成这在stream.txt文件。

Produces this in the stream.txt file.

3 4/5/2011 9:41:27 AM 807
4 4/5/2011 9:41:32 AM 812
5 4/5/2011 9:41:37 AM 817
6 4/5/2011 9:41:42 AM 822
7 4/5/2011 9:41:47 AM 826
8 4/5/2011 9:41:52 AM 831
9 4/5/2011 9:41:57 AM 836
10 4/5/2011 9:42:02 AM 841
11 4/5/2011 9:42:07 AM 799

我给这输出假设是各行之间的时间将必须是恰好5000毫秒加上它需要执行循环的其余部分可能给出不同而不同,有可能是一个未知的延迟,由于磁盘IO的时间。我的问题是看线10和11以及减法让我有4,958毫秒的差异。所以我的问题是你到底是怎么回事呢?这怎么可能获得低于5000毫秒的差异,当我告诉线程在完成过程之前休眠5000毫秒。我在想什么?

My assumption for this output would be that the time between each line would have to be exactly 5000 milliseconds plus the time it takes to execute the rest of the loop which could vary given that there could be an unknown delay due to disk IO. My problem is that looking at lines 10 and 11 and subtracting gives me a difference of 4,958 milliseconds. So my question is what the heck is going on there? How is it possible to get a difference of less than 5000 milliseconds when I have told the thread to sleep for 5000 milliseconds before completing the process. What am I missing?

推荐答案

实施意见建议:如果你需要定时线程内precision,而不是一个Do /循环(与的Thread.Sleep ),只需使用 System.Timers.Timer的 类(这是早在pre-.NET天非常不同于旧的WinForms定时器对象)。这将让你指定一个时间跨度方法调用之间。

Implementation Suggestion: If you need timing precision, instead of a Do/Loop inside of a thread (with Thread.Sleep), just use an instance of the System.Timers.Timer class (this is very different from the old WinForms "Timer" object back in pre-.NET days). This will let you specify a TimeSpan between method calls.

虽然,我不能保证在 Thread.sleep代码真正的precision与一个定时器实例(我只是摆出了定时器会更准确,因为计时是它的主要功能)...但也许有人可以编写一个简单的测试?

Although, I can't vouch for true "precision" between Thread.Sleep vs. a Timer instance (I just assumed a Timer would be more accurate, given that Timekeeping is its primary function)... but perhaps someone could write up a quick test?