2004. szeptember 14., kedd

How to wait for a file to be created


Problem/Question/Abstract:

Does anyone have code that will wait for a file to be created? In particular I'm trying to come up with code that has pretty much a 0% processor usage.

Answer:

The following function consumes very litte CPU while waiting for a file to be created:

function WaitForFile(FileName: string): Boolean;
{Wait for a file to be created. Tracks the directory were the file will be created.
Returns true if file exists, false on error.}
var
  WaitHandle: THandle;
begin
  Result := False; {Let's assume we failed}
  WaitHandle := FindFirstChangeNotification(PChar(ExtractFilePath(FileName)),
    False, FILE_NOTIFY_CHANGE_FILE_NAME);
  if (INVALID_HANDLE_VALUE = WaitHandle) then
  begin
    {The path to the file does not exists}
    Exit;
  end;
  repeat
    if WaitForSingleObject(WaitHandle, INFINITE) = WAIT_OBJECT_0 then
    begin {Something happenned in the directory}
      if FileExists(FileName) then
      begin
        result := True;
        Break; {My file has been created, exit}
      end;
      {My file is not there, keep on}
      if not FindNextChangeNotification(WaitHandle) then
      begin
        {Something happened to the directory, maybe it was deleted}
        Break;
      end;
    end;
  until
    False;
  FindCloseChangeNotification(WaitHandle);
end;

Nincsenek megjegyzések:

Megjegyzés küldése