Home > other >  Digital clock in C# (simulator) console app
Digital clock in C# (simulator) console app

Time:12-26

This is my code for simulate digital clock in C#. Is this correct?

How can I optimize this code? Does this code consume a lot of RAM? What is your suggested solution?

namespace clock
{
    class Program
    {
        static void Main(string[] args)
        {
            int h=0, m=0, s = 0;
     
            for (; s<=60; s  )
            {
                    Console.WriteLine(string.Format("{0}:{1}:{2}",h,m,s));
                   // Thread.Sleep(10);
                   if (s == 59) {
                        if (m == 59) {
                            if (h == 24) {
                                h = 0;
                                m = 0;
                                s = 0;
                            }
                            h  ;
                            m = 0;
                            s = 0;
                        }
                        m  ;
                        s = 0;
                    }

                }

                Console.ReadKey();
        }
    }
}

CodePudding user response:

there is a System.Timers.Timer class for that, you can refer to this Link which explains it (see example section): https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=net-6.0

CodePudding user response:

It's better to use System.Threading.Timer Class , check the link https://docs.microsoft.com/en-us/dotnet/standard/threading/timers

CodePudding user response:

You need to use Timer class. For more information, have a look in the following post: Live Clock in C#

CodePudding user response:

You can use new PeriodicTimer

async Task Main()
{
    var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
    int h = 0, m = 0, s = 0;

    while (await timer.WaitForNextTickAsync())
    {
        Console.WriteLine(string.Format("{0}:{1}:{2}", h, m, s));
        if (s == 59)
        {
            if (m == 59)
            {
                if (h == 24)
                {
                    h = 0;
                    m = 0;
                    s = 0;
                }
                h  ;
                m = 0;
                s = 0;
            }
            m  ;
            s = 0;
        }
        s  ;
        if (s > 60) { break; }
    }

    Console.Read();
}
  • Related