【问题标题】:Share stopwatch between threads在线程之间共享秒表
【发布时间】: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


【解决方案1】:

不要在多线程上“努力”:只需锁定连接的 Stopwatch 对象即可更新/读取它!

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

稍后在另一个线程中:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 所以我应该为秒表创建另一个静态类?
    • 我不知道这是否能解决您的问题。是否同时存在多个秒表?静态基本上就像一个单例,所以你只能拥有它的一个实例。
    • 否则,您可以创建一个静态类,其中包含一个静态字典,其中用户的唯一标识符作为键,秒表作为值。因此,您可以单独和独立地为每个用户启动秒表。我的 Visual Studio 现在不能工作,所以我不能给你测试过的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多