定时器 C#.开始、停止和获取调用之间的时间量

Timer C#. Start, stop, and get the amount of time between the calls(定时器 C#.开始、停止和获取调用之间的时间量)

本文介绍了定时器 C#.开始、停止和获取调用之间的时间量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何衡量一个函数运行了多长时间?

我正在编写一个具有可靠数据传输的 UDP 聊天.我需要在发送数据包时启动一个计时器,并在它收到来自服务器的应答(ACK - 确认)后立即停止它.

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).

这是我的代码:

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

谢谢.

推荐答案

不要使用定时器.它通常不够准确,并且为这项工作设计了一个更简单的对象:秒表类.

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.

MSDN 文档中的代码示例:

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

在您的情况下,您将在发送数据包时启动它,并在收到 ack 时停止它.

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

这篇关于定时器 C#.开始、停止和获取调用之间的时间量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:定时器 C#.开始、停止和获取调用之间的时间量

基础教程推荐