首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正确使用OmniThreadLibrary未来

正确使用OmniThreadLibrary未来
EN

Stack Overflow用户
提问于 2013-09-28 10:56:04
回答 1查看 1.1K关注 0票数 0

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

代码语言:javascript
复制
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的情况下工作正常。我想做的是:

  • 让任务在后台运行,同时等待值。
  • 如果引发异常,则希望主线程捕获它。
  • 允许主线程确定任务是否已完成或取消。

有没有可能用一个非阻塞函数来完成所有这些任务呢?

提前谢谢你,

V。

编辑:添加问题

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-28 11:57:29

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

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

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

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

异常将自动转发到代码读取未来结果的位置。由于您没有在任何地方读取结果,所以只需在if assigned(Task.FatalException)处理程序中使用OnTerminated。(顺便说一句,在终止处理程序中,IsDone始终是真的。)

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

使用Task.IsCancelled

所有这些都被记录在 chapter of the Parallel Programming with the OmniThreadLibrary的书中。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19066165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档