Question

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:

  • let the task run in the background while waiting for the value
  • if an exception is raised, I want the main thread to catch it
  • allow the main thread to determine if the task was completed or cancelled

Is it possible do a non-blocking function that would do all these?

Thank you in advance,

V.

EDIT: add the question

Was it helpful?

Solution

let the task run in the background while waiting for the value

You can wait on a result in few different ways:

  • Call Task.Value which will block until the value is computed.
  • Call Task.IsDone periodically, then call Task.Value when IsDone returns True.
  • Call Task.TryValue periodically.
  • Get the value in the termination (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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top