Nadav Freedman
Nadav Freedman

Reputation: 43

C# - Using Thread.Sleep precisely in a console application

I'm a beginner programmer who learns c# and I wanted to make a text-based snake game in the console window. Now, the game works fairly well but I encounter a problem using the Thread.Sleep() method to pause the code for a specific amount of milliseconds.

The problem is that whenever I try to pause the game for a specific time, it appears to pause for a few milliseconds longer. And since that's a snake game, that's a pretty big problem.

What I tried to do:

while (true)
            {
                double startingTime = DateTime.Now.TimeOfDay.Milliseconds;
                //code
                double lag = DateTime.Now.TimeOfDay.Milliseconds - startingTime;
                Thread.Sleep((int)Math.Round(25 - lag));
                double finalTime = DateTime.Now.TimeOfDay.Milliseconds - startingTime;
                Console.Title = string.Format("Time: {0}", finalTime);
            }

I know for a fact that the code takes about 6 ms to run, so I tried to mesure it and subtract it from the time it supposed to wait between every move. Sometimes it works properly, but more often than not The Console title says it took 31 ms...

I'd really appreciate any suggestion, and if you know a better way to pause the code from running for a precise amount of time, I'll be glad to know :)

SOLVED: I ended up using a stopwatch, like Tamir Suggested, thanks for everyone who helped :D

Upvotes: 3

Views: 971

Answers (1)

Tamir
Tamir

Reputation: 2533

Well, for very precise timing, you should use multimedia timers. Next best choice would be Stopwatch

Upvotes: 4

Related Questions