Timer C#. Start, stop, and get the amount of time between the calls(定时器 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#.开始、停止和获取调用之间的时间量
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01