Thread taking 100% CPU

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());
}
}
}
}
 
D

Dick Grier

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.
 
M

Michel Racicot

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
 
P

Phil Wilson

It's up to you - how important is it to respond quickly? If once a second is
ok, sleep for a second.
 
S

Stanimir Stoyanov

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.
 
D

Dick Grier

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top