I have multiple services processing some files. Each service must have exclusive access to the file while processing. I solved this problem a while ago by creating a global mutex that uses some temp files, something like this:
function AppLocked: boolean;
begin
result := FileExists(GetTempDir + '__MUTEX__' + LockExt);
end;
procedure AppLock;
var
F: TextFile;
begin
if FileExists(GetTempDir + '__MUTEX__' + LockExt) then
exit
else
try
AssignFile(F, GetTempDir + '__MUTEX__' + LockExt);
Rewrite(F);
Writeln(F, DateTimeToStr(Now));
CloseFile(F);
except
end;
end;
procedure AppUnLock;
begin
if FileExists(GetTempDir + '__MUTEX__' + LockExt) then
SysUtils.DeleteFile(GetTempDir + '__MUTEX__' + LockExt);
end;
This works pretty good, and I don’t want to fix something that works, but I just wonder, is there a better solution?
An actual Mutex (as in win32 Mutex) is the preferred method.