Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Show the time running in console?

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?

like image 308
ale Avatar asked Dec 28 '22 22:12

ale


2 Answers

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');
        }
like image 94
Aliostad Avatar answered Jan 07 '23 04:01

Aliostad


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.

like image 43
NateTheGreat Avatar answered Jan 07 '23 02:01

NateTheGreat