I'm looking to build a routine that is responsible for executing any action via procedure (Tproc) using Tasks, while displaying a loading screen, without freezing the system's main form. An extra detail is that it is also capable of capturing a possible exception that the action may have generated.
I built the code below, which works well, but sometimes something goes wrong and the loading screen ends up not closing, remaining always present on the screen.
Any suggestions will be welcome. Thanks.
type
TLoadingClass= class
strict private
class var FForm: TForm;
public
class procedure ActionAndWait(Action: Tproc);
end;
class procedure TLoadingClass.ActionAndWait(Action: Tproc);
var
aTask: ITask;
vException: Pointer;
begin
vException := nil;
FForm := TLoadingForm.Create(nil);
try
aTask := TTask.Run(procedure
begin
try
try
Action; {Run Action}
except on E: Exception do
vException := @E {Capture Exception}
end
finally
while not FForm.Showing do {Wait for the form to be created, if the action is very quick.}
Sleep(1);
TLoadingForm(FForm).Hide;
TLoadingForm(FForm).Close;
end;
end);
TLoadingForm(FForm).ShowModal; {Show the loading form}
finally
TTask.WaitForAll(aTask);
FreeAndNil(FForm);
if Assigned(vException) then
raise Exception(@vException);
end;
end;
Call example
TLoadingClass.ActionAndWait(
procedure
begin
try
Sleep(5000);
raise Exception.Create('Test');
except on E: Exception do
ShowMessage(E.Message);
end;
end);
TLoadingForm(
calls insideTThread.Synchronize(
and let the main UI thread schedule the form updates for you.