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
?
No, there is no API that would make it possible to be notified when opening a file becomes possible. Programs that monitor this kind of activity (e.g. ProcessMonitor) use a file system driver (link).
Consider giving up on a test opening of the file though, as it introduces a possibility that the file becomes unavailable again in between a test opening and actual opening for processing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With