定时器 C#。开始、停止和获取通话之间的时间量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13767561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Timer C#. Start, stop, and get the amount of time between the calls
提问by user1886060
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).
我正在用可靠的数据传输编写 UDP 聊天。我需要在发送数据包时启动一个计时器,并在收到来自服务器的响应(ACK - 确认)后立即停止它。
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.
谢谢你。
采纳答案by David
Don't use a Timer. It's not usually accurate enough, and there's a simpler object designed for just this work: The Stopwatchclass.
不要使用计时器。它通常不够准确,并且有一个更简单的对象专为这项工作而设计:Stopwatch类。
Code sample from the MSDN documentation:
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);
}
}
In your case, you'd start it when the packet is sent, and stop it when the ack is received.
在您的情况下,您会在发送数据包时启动它,并在收到 ack 时停止它。
回答by Honza Brestan
Stopwatchis so much better than any timer for this.
Stopwatch这比任何计时器都要好得多。
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// Your code here.
stopwatch.Stop();
And then you can access the Elapsedproperty (of type TimeSpan) to see the elapsed time.
然后您可以访问Elapsed属性(类型TimeSpan)以查看经过的时间。

