In my thread code I need to wait for a file to be unlocked in order to process it further.
The file is potentially locked by another foreign thread(s) which I can't control.
Currently i use this code in my thread:
...
while IsFileInUse(FileName) and not Terminated do
begin
Sleep(100);
end;
// process the file
IsFileInUse code:
function IsFileInUse(const FileName: string): Boolean;
var
Handle: HFILE;
begin
Handle := CreateFile(PChar(FileName),
GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (Handle = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(Handle);
end;
Is there a better and more efficient way to avoid the Sleep?