【问题标题】:Correct Way to Use OmniThreadLibrary Future使用 OmniThreadLibrary Future 的正确方法
【发布时间】:2013-09-28 10:56:04
【问题描述】:

我目前正在试验 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。我想做的是:

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

是否有可能做一个非阻塞函数来完成所有这些?

提前谢谢你,

V.

编辑:添加问题

【问题讨论】:

    标签: multithreading delphi omnithreadlibrary


    【解决方案1】:

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

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

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

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

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

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

    使用Task.IsCancelled

    所有内容都记录在Parallel Programming with the OmniThreadLibrary 书籍的Future chapter 中。

    【讨论】:

    • 你的博客很不错。这是在不阻塞的情况下等待值的正确方法吗? '漫长的等待;而不是 Task.TryValue(100, Value) 则开始 Sleep(500); Application.ProcessMessages;结尾; '
    • 这是其中一种方式。
    猜你喜欢
    • 2014-04-24
    • 1970-01-01
    • 2021-01-08
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2019-06-28
    • 1970-01-01
    相关资源
    最近更新 更多