定时器C#。启动,停止,并得到了时间量的调用之间 [英] Timer C#. Start, stop, and get the amount of time between the calls

查看:337
本文介绍了定时器C#。启动,停止,并得到了时间量的调用之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我写的UDP聊天可靠的数据传输。我需要启动一个定时器,当一个数据包发送和接收来自服务器(ACK-确认)答案尽快停止。 这是我的code:

I'm writing 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;
           }

感谢你。

推荐答案

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

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样品:<​​/ P>

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#。启动,停止,并得到了时间量的调用之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆