How Show the time running in console?
Asked Answered
A

2

5

C# I need to show the time running while the process is doing, shows the seconds increasing, normally: 00:00:01, 00:00:02, 00:00:03..... etc.

I'm using this code:

var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();

//here is doing my process
stopwatch.Stop();

when the process stop, I show the time ELAPSED, with this:

TimeSpan ts = stopwatch.Elapsed;

...and this:

{0} minute(s)"+ " {1} second(s)", ts.Minutes, ts.Seconds, ts.Milliseconds/10.

this show the total time elapsed, But I need show the time running in console.

How can I do this?

Allergen answered 19/4, 2011 at 13:58 Comment(0)
W
7

Try

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
    Console.Write(stopwatch.Elapsed.ToString());
    Console.Write('\r');
}

UPDATE

To prevent display of milliseconds:

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        while (true)
        {
            TimeSpan timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(stopwatch.Elapsed.TotalSeconds));
            Console.Write(timeSpan.ToString("c"));
            Console.Write('\r');
        }
Whiles answered 19/4, 2011 at 14:2 Comment(2)
ok. so how can I hide the miliseconds? only shows hour:minutes:secondsAllergen
Use stopwatch.Elapsed.ToString("hh:mm:ss") Whiles
K
3

If I understand correctly, you are wanting to continually update the timespan on the console while the work is still proceeding. Is that correct? If so, you will need to either do the work in a separate thread, or update the console in a separate thread. One of the best references I've seen for threading is http://www.albahari.com/threading/.

Hope this helps.

Kalong answered 19/4, 2011 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.