I am trying to make a countdown function which would stop when the timer reaches 0. What is happening so far is that when the timer reaches 0 (and I haven't pressed any key) it keeps spamming me with the default message and it doesn't stop until I click a button.
I would like to insert some code inside OnTimedEvent
which would stop the timer (once it hits zero, display the message and stop spamming me). I have tryed multiple variations of aTimer.Stop
aTimer.Enabled = false;
etc.
I get an error
The name 'aTimer' does not exist in the current context.
Code:
using System; using System.Timers; namespace MyProject { class Program { static void Main(string[] args) { Console.WriteLine("Main thread still running"); Console.WriteLine("Press X to save the world."); Console.WriteLine("You have 10 SECONDS!"); System.Timers.Timer aTimer = new System.Timers.Timer(1000); aTimer.Elapsed += OnTimedEvent; aTimer.Enabled = true; ConsoleKeyInfo input = Console.ReadKey(true); switch (input.KeyChar) { default: Console.WriteLine("Blah blah"); aTimer.Enabled = false; break; } Console.ReadKey(); } private static int _countDown = 10; // Seconds private static bool dMade = false; static void OnTimedEvent(object source, ElapsedEventArgs e) { if (dMade == false) { if (_countDown-- <= 0) { Console.WriteLine("You have doomed us all! DOOMED US ALL I TELL YOU!!!"); } else { Console.CursorLeft = 0; Console.ForegroundColor = ConsoleColor.Red; Console.Write(_countDown + " "); Console.ForegroundColor = ConsoleColor.Gray; } } else { Console.WriteLine("Success! The world is saved. Congrats!"); } }