Reading in NetworkStream = using 100% CPU

I am reading from NetworkStream, which is in a while loop. The problem is that I see 100% CPU usage. Is there any way to stop this?

Here is what I still have:

while (client != null && client.Connected) { NetworkStream stream = client.GetStream(); data = null; try { // Check if we are still connected. if (client.Client.Poll(0, SelectMode.SelectRead)) { byte[] checkConn = new byte[1]; if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0) { throw new IOException(); } } if (stream.DataAvailable) { //Read the first command WriteToConsole("Waiting for next command"); data = ReadStringFromClient(client, stream); WriteToConsole("Received Command: " + data); } } 

... The code continues ...

ReadStringFromClient Code:

  private string ReadStringFromClient(TcpClient clientATF, NetworkStream currentStream) { int i; string builtString; byte[] stringFromClient = new byte[256]; if (clientATF.Connected && currentStream.CanRead) { i = currentStream.Read(stringFromClient, 0, stringFromClient.Length); builtString = System.Text.Encoding.ASCII.GetString(stringFromClient, 0, i); } else { return "Connection Error"; } return builtString; } 
+4
source share
3 answers

The reason you see 100% CPU utilization is because you always do something, which is the result of an endless while loop without delay.

Basic semantics:

  • Check if the client is connected.
  • Customer survey
  • Check if data is available.
  • Read data
  • Go back to step 1

Since you are in this cycle, you always do something, whatever that is. The simplest semantics is to execute Thread.sleep () at the end of your loop. This will help you without having to make big changes. However, you will introduce a delay of what sleep time is, and this is actually not the right way (but may suit your situation).

The correct method is to learn about asynchronous sockets if you want to use a high-performance server or something that uses a suitable low CPU when connecting 1 or more sockets. It’s probably best to learn for a quick Google search, but I don’t remember any particularly good articles being written. The advantage of Asynchronous IO is that you will only use processor time when you need to do something. When the data is received, your method will be called to perform any processing that you must perform.

+6
source

Your code contains a lot of ... noise. You don’t need it.

The reason for 100% processor utilization is that you expect data to become available. You do not need to do this. Read will block until data is available. You also do not need to recreate NetworkStream for each piece of data received.

Your code can be greatly simplified if you use StreamReader :

 using (var reader = new StreamReader(new NetworkStream(socket)) { char[] buffer = new char[512]; int received; while ((received = reader.Read(buffer, 0, buffer.Length)) > 0) { string s = new string(buffer, 0, received); Console.WriteLine(s); } } 

Read until data becomes available. The code is shown while the connection is live. You can simplify the code even more if you use ReadLine instead of reading into the char buffer.

If you don't want to block the stream until data becomes available, look at asynchronous reading.

+8
source

This is because you constantly ask the CPU to do something for you, namely, to check if there is anything in the stream.

This is a fairly common picture that you need to learn how to handle. It's called asynchronous IO, and the good news is that the .NET platform has extensive support to make it easier for you to do what you want without 100% continuous CPU usage.

The big problem is that your code runs in an infinite loop, constantly calling client.Client.Poll(0, SelectMode.SelectRead) , which immediately returns with a response. Instead, you should ask the framework to notify you when something interesting happens, for example, when data is available for reading from a network stream. And there are more than a few ways you can do this. One way is to use the BeginRead method for NetowrkStream.

Here is an example of asynchronous socket programming for a client application.

+5
source

All Articles