Question

I was just test driving my program and was looking at its process' memory usage and others. Then, I noticed my .NET program was about 50% of CPU almost always every once in awhile it would jump to 98% CPU. If you run it long enough, the program lack of better "craps out."

Is this normal?

Update:

method RemoteLink.ListenForClientConnections;
var theClient : HandleClient;
begin
    // Loop and wait for client connection.
    while true do
    begin   
        //blocks until a client has connected to the server  
        ServerClientSock := ServerSock.AcceptTcpClient; <<== Blocking 
        theClient := new HandleClient;
        theClient.startClient(ServerClientsock);

        Invoke(new UpdateClients(UpdateTheList),theClient);
    end;
end;

Actually the while loop thread in question is not the one above but the one below.

Update:

method TSerialIndicator.BigLoop;
begin
  while true do
  begin
    if TurnOnTx then
    begin
        Thread.Sleep(50);
        TxLight.BackColor := Color.Black; 
        TurnOnTx:=false;
    end;

    if TurnOnRx then
    begin
        Thread.Sleep(50);
        RxLight.BackColor := Color.Black;
        TurnOnRx:=false;
    end;
  end;
end;

This thread is started as soon as my program is loaded and runs. As you can see, if my program is not communicating the indicators on my winform don't get updated and therefore this loop just loops without any delays.

Était-ce utile?

La solution

Any time you have a while(true) style loop, regardless of language or platform, there is a risk of pegging a single core at 100% or near 100% if you don't build the loop contents correctly. In this case, I suspect you have a dual core machine, such that one core is working as fast as it can. This results in the 50% number from your question. Additionally, I suspect that the blocking function in your loop does not work as you expect, and so there's is nothing in your code that will ever give the cpu a break.

You could mitigate the issue by placing a Thread.Sleep() call into the loop, but as you likely know, this could have an unwanted side effect on your socket service such that it's not actually listening for connections all the time.

Autres conseils

This is not normal. Comment out the loop and see if you have the same problem. If you do, try putting a Thread.Sleep(milliseconds) in it to pause without burning CPU cycles. If this is not the problem, check other loops in the application.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top