定时器C#。 启动,停止,并得到调用[复制]之间的时间量(Timer C#. Start, st

2019-08-03 16:40发布

可能重复:
如何测量多久是一个函数运行?

我正在写有可靠的数据传输一个UDP聊天。 我需要启动一个定时器,当一个数据包被发送,并尽快停止其接收来自服务器(ACK - 确认)答复。

这里是我的代码:

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

谢谢。

Answer 1:

不要使用定时器。 这不是通常不够准确,并有专为眼前这个工作简单对象: 秒表类。

从MSDN文档代码示例:

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时停止。



Answer 2:

Stopwatch是如此,比这个任何计时器好得多。

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

// Your code here.

stopwatch.Stop();

然后你就可以访问Elapsed (类型属性TimeSpan )看到所经过的时间。



文章来源: Timer C#. Start, stop, and get the amount of time between the calls [duplicate]