How to use the Stopwatch class in C#.NET

By James J

Shows How to use Stopwatch In Your Application

Using below line it will create new object of stopwatch...

System.Diagnostics.Stopwatch MyStopWatch = new System.Diagnostics.Stopwatch();

After this when you want to start This StoWatch then write below line...
MyStopWatch.Start();

After that when you want to stop it then write below line...

MyStopWatch.Stop();

For display value of that stopwatch then use below code...

For Hours : MyStopWatch.Elapsed.Hours.ToString();

For Minutes : MyStopWatch.Elapsed.Minutes.ToString();

For Seconds : MyStopWatch.Elapsed.Seconds.ToString();

For MilliSeconds : MyStopWatch.Elapsed.Milliseconds.ToString();

Suppose I want to show that in how many time the data will bind in the DatGridView Control, then using below code & using stopwatch you can know the time...

System.Diagnostics.Stopwatch MyStopWatch = new System.Diagnostics.Stopwatch();

//Start StopWatch...
MyStopWatch.Start();
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From [User]", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;

//Stop StopWatch...
MyStopWatch.Stop();

//Display binding time in messagebox...
MessageBox.Show(MyStopWatch.Elapsed.Hours.ToString()+" : "+MyStopWatch.Elapsed.Minutes.ToString()+" : "+MyStopWatch.Elapsed.Seconds.ToString()+" : "+MyStopWatch.Elapsed.Milliseconds.ToString());
conn.Close();

How to use the Stopwatch class in C#.NET  (1979 Views)