Task.Run in the while loop cause a cpu usage full

Viewed 43

code here:

var localadd = IPAddress.Any;
var server = new TcpListener(localadd, 6300);
server.Start();

while (true)
{
  var client = server.AcceptTcpClient();
  Task.Run(() => ThreadProc(client));
}
// The cpu cost is as normal as usual.     

The code above could run in expectation,But! When i move the client variable out of the while loop,then it will make whole CPU usage nearly full. code here:

var localadd = IPAddress.Any;
var server = new TcpListener(localadd, 6300);
server.Start();
var client = server.AcceptTcpClient();

while (true)
{
  Task.Run(() => ThreadProc(client));
}
// The cpu cost nearly 100%!!!      

Could somebody else explain for this thing?

1 Answers
while (true)
{
  var client = server.AcceptTcpClient();
  Task.Run(() => ThreadProc(client));
}    

The idea behind this code is most likely to wait for connections to your server, and once a connection have been established, handle the processing for that client on a separate background task. So I would expect this to be working as designed. If you want to somehow parallelize processing for a single client, that should be done in the ThreadProc method, but you need to be careful to ensure your program is thread safe, so it is probably only worth while if the processing involves lots of heavy, easily parallelizeable computations.

If you change it to

var client = server.AcceptTcpClient();
while (true)
{
  Task.Run(() => ThreadProc(client));
}  

Now we have changed the behavior so that we wait for the first client to connect. Then we start infinite number of tasks to do the processing for that client. This is most likely not the desired behavior.

Also note that you should have some way for the caller to ask your server to stop accepting new connections, and possibly also to wait for any currently alive connections to finish processing.

If you do not have some special reason to use raw TCP, I would recommend using a higher level protocol if you just want to make some computers talk to each other, there are many to chose from, http, gRPC, zeroMq, etc. Most will be easier to use that writing your own protocol directly on top of tcp.

Related