Search code examples
c#socketsthread-sleep

Should I use Thread.Sleep between a socket reception and another?


I have a loop in which I have to receive N bytes of data using a socket

int bytesRead = 0;
int offset = 0;

do
{
    var buffer = new byte[N - offset];
    bytesRead = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
    Buffer.BlockCopy(buffer, 0, packet.Buffer, offset, bytesRead);
    offset += bytesRead;

    // Thread.Sleep(How much have I to sleep?);
}
while (offset < N);

packet.Buffer is where I store all data.

Should I use Thread.Sleep between a socket reception and another to wait that enough data has arrived? If yes, how many milliseconds?


Solution

  • There is no need to sleep - the socket.Receive call will block until data is available.

    From the relevant MSDN page

    ...If no data is available for reading, the Receive method will block until data is available...