我目前正在尝试使用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。我想做的是:
是否可以执行可以完成所有这些操作的非阻塞功能?
提前谢谢你,
诉P>
编辑:添加问题
答案 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中记录了所有内容。