I recently decided to build a multi player web game using ASP.NET Core and SignalR for managing the real time bidirectional communication between a client and a server. I store the data for all of the game rooms on the server inside a singleton service. I recently decided I wanted to add a game timer which changes the players turn after a certain amount of time. So I created a dictionary inside a singleton service where the key is a GUID representing the ID of a given game room and the value is a System.Timers.Timer
class instance. The logic for changing the players turn is inside the timer's OnTimedEvent
handler. Everything works as expected, but I have some concerns:
Is it safe (and performant) to store multiple (hundreds) timer instances in memory? If not, is there a better solution to this problem?
In order to perform business logic inside the timer class, I need to resolve some service dependencies by injecting an
IScopeFactory
inside the constructor. Is this an optimal approach?
I was curious if anyone is aware of how big web game systems with hundreds of thousands of concurrent games (such as chess.com for e.g.) manage to deal with this problem?
Thanks in advance!
You don't need to create multiple (hundreds) timer instances in memory. You can check the official document first and learn more about the background task.
In your scenario, you need to store key-value in the object. Then you can check the tasks that need to be completed every second in DoWork.