Search code examples
c#timespanstopwatch

Using stopwatch in a console application


I want to make a simple stopwatch in C# console. When you press S key you start the stopwatch and Q key to stop the stopwatch. And at the end the elapsed time will show in Hours:Min:Sec. Until now the stopwatch starts but when it stops it doesnt get the elapsed time.

static void Main(string[] args)
{
    Console.WriteLine("The stopwatch, press S to begin and Q to stop");
    var UserInput = Console.ReadLine();
    System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
    stopWatch.Start();

    switch (UserInput)
    {
        case "s":
            stopWatch.Start();;
            break;
        case "q":
            stopWatch.Stop();

            break;
        default:
            Console.WriteLine("You did something wrong");
            break;
    }

    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;

    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 2);
    Console.WriteLine("RunTime " + elapsedTime);

    Console.ReadLine();
}

This is the output:

https://i.sstatic.net/VKtCQ.png


Solution

  • You're missing a loop. You probably press 's' to start and when you press 'q' you're actually hitting the last Console.ReadLine()

    If you add a loop, everything works:

        static void Main(string[] args)
        {
            Console.WriteLine("The stopwatch, press S to begin and Q to stop");
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
    
            var done = false;
    
            while (!done)
            {
                var UserInput = Console.ReadLine();
    
                switch (UserInput)
                {
                    case "s":
                        stopWatch.Start();
                        break;
                    case "q":
                        stopWatch.Stop();
                        done = true;
                        break;
                    default:
                        Console.WriteLine("You did something wrong");
                        break;
                }
            }
    
            // Get the elapsed time as a TimeSpan value.
            TimeSpan ts = stopWatch.Elapsed;
    
            // Format and display the TimeSpan value. 
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 2);
            Console.WriteLine("RunTime " + elapsedTime);
    
            Console.ReadLine();
        }
    

    Hope this helps :)