【发布时间】:2015-11-19 15:57:02
【问题描述】:
我需要 ping 连接到服务器的每个用户并计算响应所需的时间。如何在从另一个线程发送数据后立即启动秒表并在主线程收到数据时停止它?
public class SocketInformation
{
public int sequenceSend { get; set; }
public int sequenceReceive { get; set; }
private Stopwatch stopwatch = new Stopwatch();
public Stopwatch GetStopwatch()
{
return stopwatch;
}
}
private async void PingInterval(Stream stream, SocketInformation socketInformation)
{
while (true) {
byte[] pingPacket = CreatePacket(2, socketInformation, null);
await stream.WriteAsync(pingPacket, 0, pingPacket.Length);
await stream.FlushAsync();
socketInformation.GetStopwatch().Start();
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
private async void ParsePacket(StreamSocket socket, SocketInformation socketInformation, byte[] packet)
{
if (packetCommand == 1)
{
Task.Run(() => PingInterval(stream, socketInformation, stopwatch));
}
else if (packetCommand == 2)
{
socketInformation.GetStopwatch().Stop();
long pingTime = socketInformation.GetStopwatch().ElapsedMilliseconds;
// Always zero as the stopwatch didn't start
}
}
【问题讨论】:
-
需要多精确?
-
@RonBeyer 只是计算主机连接的质量,为什么?
-
因为如果精度不在毫秒范围内,存储日期时间而不是使用秒表可能会更好。
-
@RonBeyer 哦,是的。应用应该会找到 ping 小于 300 毫秒的房间。
标签: c# multithreading stopwatch