Delphi - 使用并行编程库中的 IFuture 读取大文件

Delphi - Read in a Large File using IFuture from the Parallel Programming Library

我正在阅读一些大的 excel 文件,需要 "ages" 才能加载。我可以在真正需要访问它之前加载它。所以我认为这对于并行编程库中的 IFuture 来说是一个很好的用途。但我不确定如何去做,因为所有 "Future" 示例仅涵盖简单类型,例如字符串、整数等。

这是非并行代码:

xls := TsmXLSFile.Create;
xls.Open(s);

其中 "xls" 是 Excel 对象,"s" 是内存流。

"Future" 会怎么做?我会把 xls 声明为...

xls := IFuture<TsmXLSFile>

这是正确的吗?如果是,那么我是否需要像普通 TsmXLSFile 一样释放它,因为它现在是一个接口?

史蒂夫

不,你不能那样做。你会更像这样:

... // this must be a persistant object
  ismXLSFile : IFuture< TsmXLSFile >;
...

// Get started

ismXLSFile := TTask.Future< TsmXLFile > (function : TsmXLFile begin Result := TsmXLFile.Create ); end; );

ismXLSFile.Start;

// Then at some later point
xls := ismXLSFile.Value;

是的,您仍然需要释放它。 xls 不是接口对象。 (ismXLSFile 是)。

声明一个字段以获取该接口:

FXlsFuture: IFuture<TsmXLSFile>;

添加一个创建未来的方法和另一个处理加载文件的方法:

function TForm90.CreateXlsFuture: IFuture<TsmXLSFile>;
begin
  { starts loading }
  Result := TTask.Future<TsmXLSFile>(
    function: TsmXLSFile
    begin
      result := TsmXLSFile.Create;
      result.Open(s);
    end);
end;

procedure TForm90.HandleXlsFuture(AFuture: IFuture<TsmXLSFile>);
var
  xsl: TsmXLSFile;
begin
  xsl := AFuture.Value; { eventually blocks until the file is loaded }
  { do something with the file }
  xsl.Free;
end;

此外还可以查询future的Status,检查文件是否已经加载,避免阻塞。