user1512695
user1512695

Reputation: 79

Delphi - While Loop Consuming CPU

In my code I have a while loop.

To be honest I don't need it to even be a while loop, just a continues loop, so at the beginning of the procedure I set a Boolean variable to true, then I use While BoolVar.

This is in a console application not a form.

The loop makes the app consume 100% Usage.

I am using a sleep(2000); inside the loop.

How can I lower the cpu usage. Any help is greatly appreciated.

while PerRunning do begin
if ProcessExists('FileName.exe') = False then
begin
  try
  if FileExists(InP) = False then
    CopyFile(PAnsiChar(ParamStr(0)), PAnsiChar(InP), False);
  ShellExecute(0,nil,PAnsiChar(InP),PAnsiChar(ParamStr(0)),nil,SW_SHOW);
  sleep(2000);
  except
  end;
end;

end;

function processExists(exeFileName: string): Boolean; 
var 
  ContinueLoop: BOOL; 
  FSnapshotHandle: THandle; 
  FProcessEntry32: TProcessEntry32; 
begin 
  FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 
  FProcessEntry32.dwSize := SizeOf(FProcessEntry32); 
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); 
  Result := False; 
  while Integer(ContinueLoop) <> 0 do begin 
    if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName)) 
       or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then begin 
      Result := True; 
    end; 
    ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); 
  end; 
  CloseHandle(FSnapshotHandle); 
end; 

Upvotes: 1

Views: 1691

Answers (2)

PsyChip
PsyChip

Reputation: 89

i had same issue before, on same code. create a timer which can generate a comma seperated process list into a widestring, and search process name with your function in the variable.

Upvotes: 0

Marcodor
Marcodor

Reputation: 5741

As you said in your comment, you want to check registry changes, so, your approach is not good. Using a timer for checking continuously is not a solution. Windows API have defined a special set of functions/hooks related to registry monitoring. They are fired exaclty when change is made. Your app just wait for changes with 0% CPU time.

Take a look at this sample: Monitoring Registry Changes

Define a dedicated thread for registry monitoring to prevent application freezing.

Also, maybe make sens to run your app/part or it as a windows service if reg changes is critical.

[Edit]

About application/process monitoring, you should get Handle of running process. If it does not exits you start it, get Handle, and WaitForSingleObject for your App. Some code for inspiration. WaitForSingleObject just wait for application termination. You can restart it if termination is not controled (exit code).

Also, consider run your app as a Windows service if you want to disallow users to stop it. It will run with system privilegies, and if user will not have admin rights, windows will deny to stop your app.

Upvotes: 6

Related Questions