I have to work with a device, which uses TCP connection to control it. It sends 1 byte of data every 30 milliseconds and I must react to it as soon as possible. Usually, everything works fine, but sometimes Socket.ReceiveAsync() function stuck for time up to 400-800 milliseconds and then returns some number of received bytes.
I use code like this:
_socket.ReceiveTimeout = 5;
var sw = Stopwatch.StartNew();
var len = await _socket.ReceiveAsync(new ArraySegment<byte>(Buffer, Offset, Count),
SocketFlags.None)
.ConfigureAwait(false);
_logger.Info($"Reading took {sw.ElapsedMilliseconds}ms"); // usually 0-6ms, but sometimes up to 800ms
I recorded this process with Wireshark there I could see that all the data was received in time, with about 30ms interval.
I also noticed that the probability of happening of this delay is higher when you do something on your computer. Like opening the start menu or Explorer. I think, that switching to another process or garbage collection should be much faster.