none
Countdown code help RRS feed

  • Question

  • Hello,

    I am fairly new to visual studios C# and I was wondering if it was possible to add a countdown timer that showed the numbers being counted down from 60 seconds to 0 seconds in this program? If so how would I go about doing that? (I am using Visual studios C# 2019 .NET Framework).

    Thanks in advance.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace Question_1_Program
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                int x, y;
                //User inputs the current value of sensors 1 & 2 using values 0 & 1 (0 = False/Off & 1 = True/On). 
                Console.WriteLine("Input the value for sensor one (0 = False/Off, 1 = True/On):");
                x = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Input the value for sensor two (0 = False/Off, 1 = True/On):");
                y = Convert.ToInt32(Console.ReadLine());

                if (x == 1)
                {
                    //Delay is added between each message.
                    Console.WriteLine("Ensuring that mixing motor is off. Please wait...");
                    await Task.Delay(2500);
                    Console.WriteLine("Closing valve 3, and opening valves 1 and 2. Please wait...");
                    await Task.Delay(2500);
                    Console.WriteLine("Filling up tank. Please wait...");
                    await Task.Delay(2000);
                    Console.WriteLine("Mixing tank is 100% full!");
                    await Task.Delay(1200);
                    Console.WriteLine("Commencing shut down of valves 1 and 2. Please wait...");
                    await Task.Delay(1200);
                    Console.WriteLine("Valves 1 and 2 shutdown.");
                    await Task.Delay(1000);
                    Console.WriteLine("Current value for valve 1 is: 0 (False/Off).");
                    await Task.Delay(1000);
                    Console.WriteLine("Current value for valve 2 is: 0 (False/Off).");
                    await Task.Delay(1000);
                    Console.WriteLine("Current value for valve 3 is: 0 (False/Off).");
                    await Task.Delay(1000);
                    Console.WriteLine("Current value for mixing motor is: 0 (False/Off).");
                }

                if (y == 1)
                {
                    Console.WriteLine("Ensuring valves 1, 2, and 3 are sealed. Please wait...");
                    await Task.Delay(2000);
                    Console.WriteLine("Valves 1, 2 and 3 are sealed. Preparing mixing motor. Please wait...");
                    await Task.Delay(4000);
                    Console.WriteLine("Mixing motor initialized. Please wait 60 seconds...");
                    //Add 60 second timer here.
                    await Task.Delay(2000);
                    Console.WriteLine("Commencing shutdown of mixing motor. Please wait...");
                    await Task.Delay(2000);
                    Console.WriteLine("Mixing motor shutdown. Opening valve 3. Please wait...");
                    await Task.Delay(1500);
                    Console.WriteLine("Valve 3 opened. Transfering paint to storage tank. Please wait...");
                    await Task.Delay(4000);
                    Console.WriteLine("All paint has been successfully transfered to storage tank. Shutting off valve 3. Please wait...");
                    await Task.Delay(2000);
                    Console.WriteLine("Valve 3 is sealed. Mixing tank is now 0% full.");
                    await Task.Delay(2000);
                    Console.WriteLine("Current value for valve 1 is: 0 (False/Off).");
                    await Task.Delay(1000);
                    Console.WriteLine("Current value for valve 2 is: 0 (False/Off).");
                    await Task.Delay(1000);
                    Console.WriteLine("Current value for valve 3 is: 0 (False/Off).");
                    await Task.Delay(1000);
                    Console.WriteLine("Current value for mixing motor is: 0 (False/Off).");
                }
                Console.ReadLine();
            }
        }
    }

    Thursday, March 5, 2020 12:42 AM

Answers

  • The following does a count down which is done on the first line of the console using a class to control where text/output is written.

    using System;
    using System.Threading.Tasks;
    using static ConsoleApp2.ConsoleHelpers;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                Console.CursorVisible = false;
                for (int index = 61; index-- > 0;)
                {
                    WriteText($"Count down: {index}", 0, 0,false);
                    await Task.Delay(1000);
                }
    
                Console.CursorVisible = true;
                Console.Clear();
                WriteText("Finished work!!!", 0, 0);
                Console.ReadLine();
            }
        }
    }
    

    Backend class

    using System;
    using System.Threading.Tasks;
    
    namespace ConsoleApp2
    {
        public static class ConsoleHelpers
        {
            public static string ReadLineWithTimeout(TimeSpan? timeout = null)
            {
    
                TimeSpan timeSpan = timeout ?? TimeSpan.FromSeconds(1);
                Task<string> task = Task.Factory.StartNew(Console.ReadLine);
                string result = (Task.WaitAny(new Task[] { task }, timeSpan) == 0) ? task.Result : string.Empty;
    
                return result;
    
            }
            public static void WriteText(string value, int positionLeft, int positionTop = 1, bool restorePosition = true)
            {
    
                int originalRow = Console.CursorTop;
                int originalCol = Console.CursorLeft;
    
                int width = Console.WindowWidth;
    
                try
                {
    
                    positionLeft = positionLeft % width;
    
                    Console.SetCursorPosition(positionLeft, positionTop);
                    Console.Write(value);
    
                    if (restorePosition)
                    {
                        Console.SetCursorPosition(originalRow, originalCol);
                    }
    
                }
                catch (Exception e1)
                {
                    Console.Write(value);
                }
            }
    
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, March 5, 2020 1:21 AM
    Moderator

All replies

  • The following does a count down which is done on the first line of the console using a class to control where text/output is written.

    using System;
    using System.Threading.Tasks;
    using static ConsoleApp2.ConsoleHelpers;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                Console.CursorVisible = false;
                for (int index = 61; index-- > 0;)
                {
                    WriteText($"Count down: {index}", 0, 0,false);
                    await Task.Delay(1000);
                }
    
                Console.CursorVisible = true;
                Console.Clear();
                WriteText("Finished work!!!", 0, 0);
                Console.ReadLine();
            }
        }
    }
    

    Backend class

    using System;
    using System.Threading.Tasks;
    
    namespace ConsoleApp2
    {
        public static class ConsoleHelpers
        {
            public static string ReadLineWithTimeout(TimeSpan? timeout = null)
            {
    
                TimeSpan timeSpan = timeout ?? TimeSpan.FromSeconds(1);
                Task<string> task = Task.Factory.StartNew(Console.ReadLine);
                string result = (Task.WaitAny(new Task[] { task }, timeSpan) == 0) ? task.Result : string.Empty;
    
                return result;
    
            }
            public static void WriteText(string value, int positionLeft, int positionTop = 1, bool restorePosition = true)
            {
    
                int originalRow = Console.CursorTop;
                int originalCol = Console.CursorLeft;
    
                int width = Console.WindowWidth;
    
                try
                {
    
                    positionLeft = positionLeft % width;
    
                    Console.SetCursorPosition(positionLeft, positionTop);
                    Console.Write(value);
    
                    if (restorePosition)
                    {
                        Console.SetCursorPosition(originalRow, originalCol);
                    }
    
                }
                catch (Exception e1)
                {
                    Console.Write(value);
                }
            }
    
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, March 5, 2020 1:21 AM
    Moderator
  • using System;
    using System.Timers;
    
    public class Example
    {
       private static System.Timers.Timer aTimer;
       private static int no = 60;
    
       public static void Main()
       {
          SetTimer();
    
          
         }
    
       private static void SetTimer()
       {
            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(2000);
            // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }
    
        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            Console.WriteLine(no);
    	no--;
    	if(no == 0)
    	{
    	   aTimer.Enabled = false;
    
          	  aTimer.Stop();
              aTimer.Dispose();
          
          	   Console.WriteLine("Terminating the application...");
    
    	}
        }
    }
    

    Thursday, March 5, 2020 7:56 AM
  • Hi

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer. So that it will help other members to find the solution quickly if they face the similar issue.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, March 16, 2020 5:34 AM
    Moderator