正确使用OmniThreadLibrary未来的方法

时间:2013-09-28 10:56:04

标签: multithreading delphi omnithreadlibrary

我目前正在尝试使用OmniThreadLibrary。随函附上我的代码:

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;

我会调用LongWait(),它可以正常运行而不会阻止UI。我想做的是:

  • 让任务在等待值
  • 的同时在后台运行
  • 如果引发异常,我希望主线程能够抓住它
  • 允许主线程确定任务是否已完成或取消

是否可以执行可以完成所有这些操作的非阻塞功能?

提前谢谢你,

编辑:添加问题

1 个答案:

答案 0 :(得分:6)

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

您可以通过几种不同的方式等待结果:

  • 调用Task.Value将阻止,直到计算出值。
  • 定期致电Task.IsDone,然后在Task.Value返回IsDone时致电True
  • 定期致电Task.TryValue
  • 在终止(OnTerminated)处理程序中获取值。

if an exception is raised, I want the main thread to catch it

异常将自动转发到代码读取未来结果的位置。由于您没有在任何地方阅读结果,因此您只需在if assigned(Task.FatalException)处理程序中使用OnTerminated即可。 (BTW,IsDone在终止处理程序中始终为真。)

allow the main thread to determine if the task was completed or cancelled

使用Task.IsCancelled

Future chapter本书的Parallel Programming with the OmniThreadLibrary中记录了所有内容。