I am writing an application that needs to wait until a file exists in a directory. I have tried multiple approaches to this, and the only solution that works is using Sleep/Application.ProcessMessages.
Here's what I have tried:
Using Sleep/Application.ProcessMessages:
Result := False;
for i := 0 to iTimeout do
begin
if FileExists(fileName) do
begin
updateStatus('Conversion Completed');
Result := True;
Break;
end;
updateStatus(Format('Checking for file: %d Seconds', [i]));
Application.ProcessMessages;
Sleep(1000);
end;
This method works, except that I can't close the application while it's waiting. Also there are well documented issues with using Sleep/Application.ProcessMessages that I would rather avoid.
Using TThread/TEvent:
type
TMyThread = class(TThread)
private
FEventDone: TEvent;
public
constructor Create(CreateSuspended: boolean);
destructor Destroy;
procedure Execute; override;
property EventDone: TEvent read FEventDone;
end;
TformThreading = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
waitThread: TMyThread;
{ Private declarations }
public
{ Public declarations }
end;
var
formThreading: TformThreading;
implementation
{$R *.dfm}
{ TformThreading }
procedure TformThreading.Button1Click(Sender: TObject);
var
res: TWaitResult;
begin
try
waitThread.Start;
res := waitThread.EventDone.WaitFor(INFINITE);
case res of
wrSignaled: ShowMessage('wrSignaled');
wrTimeout: ShowMessage('wrTimeout');
wrAbandoned: ShowMessage('wrAbandoned');
wrError: ShowMessage('wrError');
wrIOCompletion: ShowMessage('wrIOCompletion');
end;
except
on E: Exception do
begin
ShowMessage(E.Message);
end;
end;
end;
procedure TformThreading.FormCreate(Sender: TObject);
begin
waitThread := TMyThread.Create(true);
end;
procedure TformThreading.FormDestroy(Sender: TObject);
begin
waitThread.Free;
end;
{ TMyThread }
constructor TMyThread.Create(CreateSuspended: boolean);
begin
inherited Create(CreateSuspended);
FEventDone := TEvent.Create;
end;
destructor TMyThread.Destroy;
begin
FEventDone.Free;
end;
procedure TMyThread.Execute;
begin
for i := 0 to iTimeout do
begin
if FileExists(fileName) do
begin
FEventDone.SetEvent;
Break;
end;
Application.ProcessMessages;
Sleep(1000);
end;
end;
I can't seem to get this to not freeze my main thread while it is waiting, but this seems like the correct approach if I can work out the freezing issue.
What is my best approach to solve my problem?