Author: Jonas Bilinkevicius
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:
1 2 function WaitForFile(FileName: string): Boolean;
3 {Wait for a file to be created. Tracks the directory were the file will be created.4 Returns true if file exists, false on error.}5 var6 WaitHandle: THandle;
7 begin8 Result := False; {Let's assume we failed}9 WaitHandle := FindFirstChangeNotification(PChar(ExtractFilePath(FileName)),
10 False, FILE_NOTIFY_CHANGE_FILE_NAME);
11 if (INVALID_HANDLE_VALUE = WaitHandle) then12 begin13 {The path to the file does not exists}14 Exit;
15 end;
16 repeat17 if WaitForSingleObject(WaitHandle, INFINITE) = WAIT_OBJECT_0 then18 begin{Something happenned in the directory}19 if FileExists(FileName) then20 begin21 result := True;
22 Break; {My file has been created, exit}23 end;
24 {My file is not there, keep on}25 ifnot FindNextChangeNotification(WaitHandle) then26 begin27 {Something happened to the directory, maybe it was deleted}28 Break;
29 end;
30 end;
31 until32 False;
33 FindCloseChangeNotification(WaitHandle);
34 end;