Reputation: 3
I want to send a bunch of data with low latency to another device using UDP.
This is a short snippet that reproduces the problem:
private void Form1_Shown(object sender, EventArgs e)
{
UdpClient udpClient = new UdpClient(9000);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 7000);
new Thread(() =>
{
Stopwatch stopwatch = new Stopwatch();
byte[] buffer = new byte[1922];
while (true)
{
stopwatch.Start();
udpClient.Send(buffer, buffer.Length, endPoint);
stopwatch.Stop();
Console.WriteLine("Sending took " + stopwatch.ElapsedMilliseconds + "ms"); // stopwatch.ElapsedMilliseconds gets higher and higher
Thread.Sleep(10);
}
}).Start();
}
The buffer has the same size everytime (in the loop) and the packets are sent every 10 ms...normally.
But approx. every 300ms it takes 1 additional millisecond to send so after a short time it takes already 1 minute to send a packet.
What is the problem there and how do I fix it?
Upvotes: 0
Views: 442
Reputation: 1520
The problem is in your measurement: you're not resetting your stopwatch anywhere. Instead of calling the stopwatch.Start()
method, call the Restart()
method instead.
Restart() : Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
while (true)
{
stopwatch.Restart();
udpClient.Send(buffer, buffer.Length, endPoint);
stopwatch.Stop();
Console.WriteLine("Sending took " + stopwatch.ElapsedMilliseconds + "ms");
Thread.Sleep(10);
}
Upvotes: 2