Timer C#. Start, stop, and get the amount of time between the calls

48,113

Solution 1

Don't use a Timer. It's not usually accurate enough, and there's a simpler object designed for just this work: The Stopwatch class.

Code sample from the MSDN documentation:

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value. 
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

In your case, you'd start it when the packet is sent, and stop it when the ack is received.

Solution 2

Stopwatch is so much better than any timer for this.

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

// Your code here.

stopwatch.Stop();

And then you can access the Elapsed property (of type TimeSpan) to see the elapsed time.

Share:
48,113
user1886060
Author by

user1886060

Updated on December 13, 2020

Comments

  • user1886060
    user1886060 over 3 years

    Possible Duplicate:
    How to measure how long is a function running?

    I'm writing a UDP chat with reliable data transfer. I need to start a timer when a packet is sent, and stop it as soon it receives an answer from the server (ACK - acknowledgment).

    Here is my code:

     private void sendButton_Click(object sender, EventArgs e)
     {
         Packet snd = new Packet(ack, textBox1.Text.Trim());
         textBox1.Text = string.Empty;
         Smsg = snd.GetDataStream();//convert message into array of bytes to send.
         while (true)
         {
            try
             {  // Here I need to Start a timer!
               clientSock.SendTo(Smsg, servEP); 
               clientSock.ReceiveFrom(Rmsg, ref servEP);
               //Here I need to stop a timer and get elapsed amount of time.
    
               Packet rcv = new Packet(Rmsg);
               if (Rmsg != null && rcv.ACK01 != ack)
                   continue;
    
               if (Rmsg != null && rcv.ACK01 == ack)
               {
                this.displayMessageDelegate("ack is received :"+ack);
                ChangeAck(ack);
                break;
               }
    

    Thank you.