在不消耗 CPU 时间的情况下在线程中读取 INI 文件

Read INI File in a thread without consuming CPU time

如何在线程中读取 .ini 文件而不消耗那么多 CPU 时间?线程将在 运行 时 运行,这意味着 while 没有延迟。

在 .ini 上搜索值的代码是:

var
  Leitura : TIniFile;
begin
  Result  := False;
  Leitura := TIniFile.Create('File.ini');

  if Leitura.ValueExists('KEY', ValueToSearch) then Result := True;

  Leitura.Free;

但是由于这个函数运行处于无限循环中,它消耗了CPU时间,我需要解决这个问题。

您可以使用 FindFirstChangeNotification API and only check the value when the file has changed. Delphi versions contained a component TShellChangeNotifier in the unit ShellCtrls.pas which was a wrapper around the API function. There is furthermore an article A Directory Monitor Class For Delphi that shows how to use the ReadDirectoryChangesW Windows API function. ReadDirectoryChangesW "retrieves information that describes the changes within the specified directory". The Delphi JCL contains a component TJvChangeNotify to monitor file and directory changes, too. On Torry you can finally find a component ATFileNotification 监视文件的变化,而不是连续轮询 .INI 文件的变化,它允许监视 file/directories 变化并在发生变化时触发事件。