2 Attachment(s)
[RESOLVED] Timing problem in C#
Hi guys,
My OS is Windows 7 32-bit, and I'm using Visual Studio 2008.
In my C# program I use function Thread.Sleep(5) to cause my thread to sleep in 5(ms), and then I print the elapsed time to the screen. My code snippet:
Code:
for (int i = 0; i < 20; i++)
{
myTimer.Start();
Thread.Sleep(5);
myTimer.Stop();
dTime = myTimer.Duration;
Console.WriteLine("{0}\n", dTime);
// Thread.Sleep(1000);
}
Thread.Sleep(20000);
The strange thing is that: Depending on whether or not I comment the line Thread.Sleep(1000) (as you can see from the above code snippet), the Thread.Sleep(5) function may not work accurately. If I uncomment the line, then the function seems to work more accurately than when I comment it. Please have a look at the two pictures I attached herewith to see the results more clearly.
So, my question is what causes the inaccuracy in the second case? Is there any thing I can do to improve the accuracy in that case?
Thank you for reading my question.
Kakashi