Home »
.Net »
C# Programs
C# - How to Print Elapsed Milliseconds of Stopwatch?
Here, we are going to learn how to print elapsed milliseconds of stopwatch using Thread.Sleep() method in C#?
By Nidhi Last updated : March 29, 2023
To print elapsed milliseconds of stopwatch, we paused the program using Thread.Sleep() and then print elapsed milliseconds using ElapsedMilliseconds property of StopWatch class.
C# program to print elapsed milliseconds of stopwatch using Thread.Sleep() method
/*
* Program to print elapsed milliseconds of Stopwatch
* using Thread.Sleep() method in C#
*/
using System;
using System.Diagnostics;
using System.Threading;
class Program {
static void Main() {
Stopwatch watch = Stopwatch.StartNew();
Thread.Sleep(2000);
watch.Stop();
Console.WriteLine("Elapsed Milliseconds by ThreadSleep() :" + watch.ElapsedMilliseconds);
}
}
Output
Elapsed Milliseconds by ThreadSleep() :1999
Press any key to continue . . .
Explanation
In the above program, we created a program class that contains the Main() method. In the Main() method we created an object watch of StopWatch class and start the stopwatch using StatNew() method. Then paused the Main() thread for 2000 milliseconds then stop the stopwatch and print the elapsed time using ElapsedMilliseconds property on the console screen.
C# Thread Programs »