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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With