DSDS-0814 avatar image
0 Votes"
DSDS-0814 asked TimonYang-MSFT commented

Socket.Receive cpu full load in C# tcp server

Hello, the below code causes cpu full load for unknown reason.

     public void RecvThread()
             const int PACKET_SIZE_MAX = 16384;

             while (true)
                 if (!m_hClient.Connected || !m_hClient.Client.Connected)

                 byte[] buf = new byte[PACKET_SIZE_MAX];
                 int len;

                 // 1. Keep the data by MSG_PEEK
                 if ((len = m_hClient.Client.Receive(buf, PACKET_SIZE_MAX, SocketFlags.Peek)) <= 0)

                 // 2. Find if in these data, there is any '\r'. If not, then continue the loop again
                 int iPosOfSeperator = -1;
                 for (int i = 0; i < len; i++)
                     if (buf[i] == (byte)'\r')
                         iPosOfSeperator = i;

                 if (iPosOfSeperator == -1)

                 // 3. read the data again within a length before \r  without MSG_PEEK
                 if ((len = m_hClient.Client.Receive(buf, 0, iPosOfSeperator + 1, SocketFlags.None)) <= 0)

                 // remove the '\r'
                 len -= 1;

                 HandlePacket(buf, 0, len);
         catch (Exception)

This code will receive packets separated with '\r' char to make sure each packet are received completely

The profiler said the m_hClient.Client.Receive is using full cpu. Please help!

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

This may be the reason.

If you are using a connection-oriented Socket, the Receive method will read as much data as is available, up to the size of the buffer. If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.

Could you please provide a more complete code so that we can reproduce your question more easily?

0 Votes 0 ·

0 Answers