3
\$\begingroup\$

Just a simple timer application for review. Stop and start the timer from the command line.

The plan is to use this in a poker application to fold out a player if they don't act after a time period (call the clock on them). I was trying to use async await but it did not seem like the right tool for this.

MyTimer myTimer = new MyTimer();
while (true)
{
    string readLine = Console.ReadLine();
    if (readLine == "stop")
    {
        myTimer.TimerStop();
    }
    else if (readLine == "start")
    {
        myTimer.TimerStart();
    }
    else if (readLine == "q")
    {
        Environment.Exit(0);
    }
}

.

public class MyTimer
{
    private System.Timers.Timer aTimer = new System.Timers.Timer();
    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        Debug.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }

    public void TimerStop()
    {
        aTimer.Enabled = false;
        Console.WriteLine("aTimer.Enabled = false");
    }
    public void TimerStart()
    {
        aTimer.Enabled = true;
        Console.WriteLine("aTimer.Enabled = true");
    }

    public MyTimer()
    {
        aTimer.Interval = 2000;
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;
        // Start the timer
        aTimer.Enabled = true;
        Debug.WriteLine("aTimer.Enabled");
        Console.WriteLine("aTimer.Enabled");
    }
}
\$\endgroup\$
  • 2
    \$\begingroup\$ VTC can you tell me what else you are looking for? \$\endgroup\$ – paparazzo Apr 3 '18 at 16:11
3
\$\begingroup\$

Why aren't you inheriting from Timer it's not a sealed class and is disposable (and I believe must be disposed).

public class PokerTimer : Timer
{
    public PokerTimer() : this(2000)
    {

    }

    public PokerTimer(double interval) : base(interval)
    {
        AutoReset = true;
        Elapsed += OnTimedEvent;
    }

    protected override void Dispose(bool disposing)
    {
        //clean up anything you need to here or remove this override.
        base.Dispose(disposing);
    }
}

All that being said, you said this is for a game where you want to time out players so you might want to look a bit into game loops and managing state in such a loop.

\$\endgroup\$
  • \$\begingroup\$ I will look into game loops. \$\endgroup\$ – paparazzo Apr 10 '18 at 5:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.