Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 963
Nadav Freedman Avatar asked Jun 19 '26 15:06

Nadav Freedman


1 Answers

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

like image 99
Tamir Avatar answered Jun 21 '26 06:06

Tamir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!