Various answers suggest it is a bad idea to sleep inside a thread, for example: Avoid sleep. Why exactly? One reason often given is that it is difficult to gracefully exit the thread (by signalling it to terminate) if it is sleeping.
Let's say I wanted to periodically check for new files in a network folder, maybe once every 10s. This seems perfect for a thread with the priority set to low (or lowest) because I don't want the potentially time-consuming file I/O to impact my main thread.
What are the alternatives? Code is given in Delphi but would apply equally to any multi-threaded application:
procedure TNetFilesThrd.Execute();
begin
try
while (not Terminated) do
begin
// Check for new files
// ...
// Rest a little before spinning around again
if (not Terminated) then
Sleep(TenSeconds);
end;
finally
// Terminated (or exception) so free all resources...
end;
end;
A minor modification might be:
// Rest a little before spinning around again
nSleepCounter := 0;
while (not Terminated) and (nSleepCounter < 500) do
begin
Sleep(TwentyMilliseconds);
Inc(nSleepCounter);
end;
but this still involves a Sleep...