So I am simulating this smartphone app to Windows. It's a game that runs it's logic and draw methods at a 1/60
rate. In milliseconds this is 16.6667
I've implemented this game loop:
private const double UPDATE_RATE = 1000d / 60d;
private void GameLoop()
{
double startTime;
while (GetStatus() != GameStatus.NotConnected)
{
startTime = Program.TimeInMillis;
//Update Logic
while (Program.TimeInMillis - startTime <= UPDATE_RATE)
{
//Thread.Yield(); it consumed CPU before adding this too, adding this had no effect
Thread.Sleep(TimeSpan.FromTicks(1));//don't eat my cpu
}
}
Debug.WriteLine("GameLoop shutdown");
}
Program.TimeInMillis
comes from a NanoStopwatch
class, that return the time in millis in double
. Which is useful because this gameloop has to be really accurate to make everything work.
As you probably know, the Thread.Sleep
will consume a lot of CPU here. Probably because it requires int millis
which will convert my TimeSpan
to 0 milliseconds.
I recently came across this thing called WaitHandle
, but everything I see uses int millis
. I really need to make this accurate so I actually need double millis
or microseconds/nanoseconds
.
Is there anything in C# that allows me to Wait
for x amount of microseconds. I don't mind creating something myself (like I did for the NanoStopwatch
), but I need to be pointed in the right direction. Found a lot on the internet, but everything uses int millis
and that's not accurate enough for me.
I ran some tests changing the Sleep
to use something like: UPDATE_RATE - (Program.TimeInMillis - startTime)
which isn't making my gameloop accurate.
I hope everything is clear enough, if you need more information just leave a comment.
tl;dr - Is there any way to let a thread wait for an amount of microseconds/nanoseconds
in C#
? My gameloop needs to be accurate and milliseconds isn't accurate enough for me.
Thanks in advance!