在线程之间共享秒表

Share stopwatch between threads

我需要对连接到服务器的每个用户执行 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
    }
}

您可以为秒表使用静态 class,因此它可以独立交互。

否则观察者也是个不错的主意。 https://msdn.microsoft.com/en-us/library/ff506346(v=vs.110).aspx

不要成为多线程中的 "try hard":只需将连接的 Stopwatch 对象锁定到 update/read 它!

var sw = socketInformation.GetStopwatch();
lock (sw) sw.Start();

稍后在另一个线程中:

var sw = socketInformation.GetStopwatch();
lock (sw)
{
   sw.Stop();
   long pingTime = sw.ElapsedMilliseconds;
}