1y ago · Sep 24, 2024 3:50 PM
In older C# tick loops, using inside a while-loop causes tick drift because the work execution time is added on top of the delay duration.
Using for tick loops with zero time drift:
Key Advantages:
- No Drift: Adjusts sleep intervals to account for work execution time.
- Zero Allocations: returns a with zero heap allocations per tick.
- Thread-Safe Cancellation: Gracefully exits as soon as cancels.
CODE
await Task.Delay(100)Using
CODE
PeriodicTimer CSHARP
public async Task RunGameLoopAsync(CancellationToken ct)
{
// 60 Hz tick rate (16.66 ms)
using PeriodicTimer timer = new PeriodicTimer(TimeSpan.FromMilliseconds(16.666));
while (await timer.WaitForNextTickAsync(ct))
{
// Executes exactly on interval boundaries!
UpdatePhysics();
BroadcastGameState();
}
}Key Advantages:
- No Drift: Adjusts sleep intervals to account for work execution time.
- Zero Allocations:
CODE
WaitForNextTickAsync CODE
ValueTask<bool>- Thread-Safe Cancellation: Gracefully exits as soon as
CODE
CancellationToken
GameDevSam · Indie Game Developer
Solo indie dev building games with Unity, Monogame, and cust...
Solo indie dev building games with Unity, Monogame, and cust...
The following users thanked GameDevSam for this post: