4

I made a maze game. I need a ticking timer. I have tried to create a class like this:

using System;
using System.Threading;

namespace Maze
{
    class Countdown
    {
        public void Start()
        {
            Thread.Sleep(3000);              
            Environment.Exit(1);
        }
    }
}

and calls the method Start() at the start of the code. After running it, I tried to move the avatar through the maze which failed. If I'm not mistaken, the Thread.Sleep makes the rest of my code not to work anymore. If there's a way I can do other things, please tell me.

Reinan Contawi
  • 225
  • 1
  • 6
  • 13

4 Answers4

3

The reason your current code isn't working is that calling Thread.Sleep() stops any execution on the current thread until the time given has elapsed. So if you call Countdown.Start() on your main game thread (which I guess you are doing), your game will freeze until the Sleep() call has finished.


Instead, you'll want to use System.Timers.Timer

Take a look at the MSDN documentation.

UPDATE: Now hopefully matches more your scenario

public class Timer1
 {
     private int timeRemaining;

     public static void Main()
     {
         timeRemaining = 120; // Give the player 120 seconds

         System.Timers.Timer aTimer = new System.Timers.Timer();

         // Method which will be called once the timer has elapsed
         aTimer.Elapsed + =new ElapsedEventHandler(OnTimedEvent);

         // Set the Interval to 3 seconds.
         aTimer.Interval = 3000;

         // Tell the timer to auto-repeat each 3 seconds
         aTimer.AutoReset = true;

         // Start the timer counting down
         aTimer.Enabled = true;

         // This will get called immediately (before the timer has counted down)
         Game.StartPlaying();
     }

     // Specify what you want to happen when the Elapsed event is raised.
     private static void OnTimedEvent(object source, ElapsedEventArgs e)
     {
         // Timer has finished!
         timeRemaining -= 3; // Take 3 seconds off the time remaining

         // Tell the player how much time they've got left
         UpdateGameWithTimeLeft(timeRemaining);
     }
 }
Mark Pim
  • 9,898
  • 7
  • 40
  • 59
  • what is the OnTimedEvent for? will it exit the program after 3 seconds? – Reinan Contawi Jul 15 '11 at 14:56
  • Whatever you put in `OnTimedEvent` will be executed once the timer's interval has elapsed. In other words you're telling C# 'Run this code after 3000ms have elpased'. Setting `aTimer.Enabled = true` is the line that actually starts the timer counting down. – Mark Pim Jul 15 '11 at 15:00
  • Sorry you must have the wrong idea because of my explanation is not that concise. The code I used is just an attempt. I know it would fail, I'm just trying to learn the concept. What I want to happen to the code I tried is to do something else in 3seconds. – Reinan Contawi Jul 15 '11 at 15:05
  • In that case you can just put whatever you want to happen after 3 seconds in the `OnTimedEvent` method. At that point you can always reset the timer and set it off again, or you can set it up in the first case to repeatedely call `OnTimedEvent` every 3 seconds. – Mark Pim Jul 15 '11 at 16:17
  • @Reinan Contawi - I've updated my answer to hopefully reflect better what you're trying to do. – Mark Pim Jul 15 '11 at 16:23
  • 1
    are Game.StartPlaying() and UpdateGameWithTimeLeft() your self-made method? – Reinan Contawi Jul 15 '11 at 17:15
  • i can't use the timeRemaining variable in the OnTimedEvent method. – Reinan Contawi Jul 15 '11 at 17:49
  • The code is just an example to show the kind of code you can use, substitute the appropriate code for your game as needed. Ah sorry, declare timeRemaining as a static field in the class and you'll be able to use it in the method. – Mark Pim Jul 15 '11 at 20:25
1

You're looking for the Timer class.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Why not use one of the Timer classes already included in the BCL?

Here is a comparison of the different ones (MSDN Magazine - Comparing the Timer Classes in the .NET Framework Class Library). Read it to see which one will be most suitable to your specific situation.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • I can't really understand how to use the Start() Stop() methods. Is it already built-in? Like Read() and Write()? Or would i still have to create my own method Start()? – Reinan Contawi Jul 15 '11 at 15:00
  • @Reinan Contawi - Did you read the linked article? It has examples. And all timers use _events_ to fire. – Oded Jul 15 '11 at 15:01
  • is that for Form Applications only? I using Console Application btw. – Reinan Contawi Jul 15 '11 at 15:11
  • @Reinan Contawi - No, not for form Applications only. The timers can be used in console applications too. – Oded Jul 15 '11 at 15:12
0

In addition to @Slaks resposnse can say you can use :

  1. System.Windows.Forms.Timer which is Timer on the same thread where UI stays
  2. System.Timers.Timer which is a timer but runs on another thread.

Choose is up to you, depends on your app architecture.

Regards.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • 1
    If you are interacting with the UI constantly, it maybe more beneficial to run the timer in another thread. – nbz Jul 15 '11 at 15:09
  • agree with @nEM, but final desicion in only up to you @Reinan. – Tigran Jul 15 '11 at 15:13
  • help me from the top please so i can get the concept. i'm a fast learner i just need to get it from the top. first, are my additional header files correct? System.Threading; System.Timers; – Reinan Contawi Jul 15 '11 at 15:23
  • if you want NON BLOCKING UI, use System.Timers.Timer object, but in this case yuo should care about updating your UI with Invoke on main thread, as you can not update UI not from UI thread. Look here for more detailed explanation of how to: http://stackoverflow.com/questions/661561/how-to-update-gui-from-another-thread-in-c – Tigran Jul 15 '11 at 15:29
  • ok. next is, how would i call the Start method? just Start(); ? – Reinan Contawi Jul 15 '11 at 15:31
  • please explain how this code works: Timer timer = new Timer(new TimerCallback(TimeCallBack),null,1000,50000); – Reinan Contawi Jul 15 '11 at 15:40
  • first create Timer, let's say _timer object, subscribe to Tick event, and call Run(). It's better to you to go to microsoft and see simple code sample how to do it. Just google System.Timers.Timer. – Tigran Jul 15 '11 at 15:41
  • i already have the t.Start(); how could i stop it after 200 seconds? – Reinan Contawi Jul 15 '11 at 16:04
  • Use Interval property, look at documentation I can not assist you in all code writing. Ragards. – Tigran Jul 15 '11 at 16:08
  • Finally! I have successfully made a timer. All I have to do now is to display the timer. I used t.Elapsed...t.Interval...and t.Enabled. Is it possible for me to display the timer? – Reinan Contawi Jul 15 '11 at 16:22