I am currently experimenting with OmniThreadLibrary. Enclosed is my code:
procedure TMainForm.LongWait;
begin
Task := Parallel.Future<string>(
function: string
begin
Sleep(10000);
Result := 'Done';
end,
Parallel.TaskConfig.OnTerminated(
procedure
begin
if Task.IsDone then
MessageDlg('Complete', mtInformation, [mbOK], 0)
else
MessageDlg('Exception', mtError, [mbCancel], 0)
end)
);
end;
I would call LongWait() and it works fine without blocking the UI. What I would like to do is:
Is it possible do a non-blocking function that would do all these?
Thank you in advance,
V.
EDIT: add the question
let the task run in the background while waiting for the value
You can wait on a result in few different ways:
Task.Value
which will block until the value is computed.Task.IsDone
periodically, then call Task.Value
when IsDone
returns True
.Task.TryValue
periodically.OnTerminated
) handler.if an exception is raised, I want the main thread to catch it
Exception will be automatically forwarded to the point where your code reads the future result. As you are not reading the result anywhere, you can simply use if assigned(Task.FatalException)
in the OnTerminated
handler. (BTW, IsDone
will always be true in the termination handler.)
allow the main thread to determine if the task was completed or cancelled
Use Task.IsCancelled
.
All that is documented in the Future chapter of the Parallel Programming with the OmniThreadLibrary book.