ale
ale

Reputation: 3421

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?

Upvotes: 5

Views: 13387

Answers (2)

Aliostad
Aliostad

Reputation: 81660

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');
        }

Upvotes: 7

NateTheGreat
NateTheGreat

Reputation: 2305

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.

Upvotes: 3

Related Questions