Search code examples
.netvb.netsleepthread-sleep

VB.net Inconsistant Thread Sleep Timer


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

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

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?


Solution

  • 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.

    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?