Kenny
Kenny

Reputation: 1152

Share stopwatch between threads

I need to ping every user connected to the server and calculate how much it takes to respond. How I can start the stopwatch right after sending the data from another thread and stop it when it's received on the main thread?

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
    }
}

Upvotes: 1

Views: 1677

Answers (2)

Max Yakimets
Max Yakimets

Reputation: 1235

Don't be a "try hard" at multithreading: just lock on connection's Stopwatch object to update/read it!

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

And later in another thread:

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

Upvotes: 1

eTomate
eTomate

Reputation: 241

You could use a static class for the stopwatch, so it interacts independent.

Otherwise an observer would be a neat idea too. https://msdn.microsoft.com/en-us/library/ff506346(v=vs.110).aspx

Upvotes: 0

Related Questions