Thread taking 100% CPU

  • Thread starter Thread starter Michel Racicot
  • Start date Start date
M

Michel Racicot

In my application, I have a thread that takes 100% of the CPU (Infinite
Loop)

What is the best way to prevent that? adding in a thread.sleep??? in the
While loop?

The code is the following:

// NetListener is a TCPListener

private void ListeningLoop()
{
while (Listening)
{
if (NetListener.Pending())
{
TcpClient ConnectedClient = NetListener.AcceptTcpClient();
if (ConnectedClient.Connected)
{
CurrentServer.AddClient(ConnectedClient);
_Logger.Log("New Client - " +
ConnectedClient.Client.RemoteEndPoint.ToString());
}
}
}
}
 
Try:

Thread.Sleep(1);

inside the loop.

--
Richard Grier, MVP
Hard & Software
Author of Visual Basic Programmer's Guide to Serial Communications, Fourth
Edition,
ISBN 1-890422-28-2 (391 pages, includes CD-ROM). July 2004, Revised March
2006.
See www.hardandsoftware.net for details and contact information.
 
It's working, but shouldn't the sleep parameter be greater than 1 to
minimize even more the time taken?

Also, is there another solution or is it the definitive best one?

Thank you btw
 
It's up to you - how important is it to respond quickly? If once a second is
ok, sleep for a second.
 
Do you really have to continue adding clients ad infinitum? If not, you
should consider changing the way you handle connections. E.g. only add a
client when the existing connection drops, which would not use the CPU at
its maximum.
 
Sure. Experiment.

In practice (I suspect), a number greater than 10 will not result in any
perceived improvement, and will decrease the response time of you
application to a request.

Dick

--
Richard Grier, MVP
Hard & Software
Author of Visual Basic Programmer's Guide to Serial Communications, Fourth
Edition,
ISBN 1-890422-28-2 (391 pages, includes CD-ROM). July 2004, Revised March
2006.
See www.hardandsoftware.net for details and contact information.
 
Back
Top