5
\$\begingroup\$

I want to find out the best way of creating time based events in games. Lets talk for example about Texas Holdem Poker. Server can handle thousands of tables and in every table we have timers: turn timer, hold seat timer and so on.

What is the best way of timers realization for this purpose?

Is System.Timers.Timer class can handle this or it will be more reasonable to create a separate thread with sorted time queue (for example an ascending sorted list with int values which represent time in ms remained)?

Thanks in advance, Valentin

\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

Timer can handle it, your main concern will be memory usage with thousands of requests.

A suggestion is to create an Async timer with a callback to signal the table or player of an action. The function signature is this :

Timer( TimerCallback callback, object state, uint dueTime, uint period)

so instead of keeping track of the timer queue yourself and having some heavy logic, you can just add a timer with a callback to your logic, and pass th

void HandleAction (object state)
      {
         //Do the work here
      }

      static void CreateTimer( )
      {
         Program p = new Program(); 

         Timer myTimer = new Timer
            (p.HandleAction, //method
               "Parameter to pass to the function.", //parameter
               2000,   // execute this after 2 seconds
               1000);  // Repeat every second 
      }
\$\endgroup\$
1
\$\begingroup\$

This is how I'd do it, in general programming (not just C#)

I'd have a thread to handle my timers, with an ordered queue with datetime values for all future events.

Your timer thread would look like this:

while (true)
{
    curr_date = time();
    lock(queue);
    while (queue.top.date < curr_date)
    {
        act(queue.top); // usually very simple stuff, like alerting another thread
        queue.pop();
    }
    unlock(queue);
    thread.sleep(queue.top.date - curr_date);
}

In addition, any thread who wants to add a message into your timer list, should call a function like this:

lock(queue);
queue.insert_ordered(timer);
unlock(queue);
thread.awake();

Would something like this solve your problem?

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .