Skip to content

Instantly share code, notes, and snippets.

@jpluimers
Created March 10, 2014 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpluimers/9466891 to your computer and use it in GitHub Desktop.
Save jpluimers/9466891 to your computer and use it in GitHub Desktop.
Circumvent I/O error 32 in Delphi at least for a while (in case for instance two threads want to log to the same log file at almost the same time)
//1 do not use 0=aSleepMillisecondsBetweenRetries as Sleep doesn't work predictably then: http://blogs.msdn.com/b/oldnewthing/archive/2005/10/04/476847.aspx
function AppendWithRetry(const aTextFile: TextFile; const aRetryCount: Integer = 10; const aSleepMillisecondsBetweenRetries: Integer = 1): Boolean;
var
lCount: Integer;
lIOResult: Integer;
begin
Result := False;
{$IFOPT I+}
{$DEFINE AppendWithRetry_IPlus}
{$I-}
{$ENDIF I+}
lIOResult := 0;
lCount := aRetryCount;
while lCount > 0 do
begin
Append(aTextFile);
lIOResult := IOResult;
if lIOResult = 0 then
begin
lCount := -1; // no more tries needed
Result := True;
end
else
begin
Sleep(aSleepMillisecondsBetweenRetries);
Dec(lCount);
end;
end;
{$IFDEF AppendWithRetry_IPlus}
{$I+}
if lCount = 0 then
begin // retry once more to see if we can still force a run-time-error
Append(aTextFile); // retry once more
Result := True; // when there was no I/O error, otherwise an exception gets thrown.
end;
{$ENDIF AppendWithRetry_IPlus}
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment