Search code examples
delphiparallel-processingppl

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


I'm reading in some large(ish) excel file which take "ages" to load. I can load it in before I really need to access it. So I thought this would be a good use for an IFuture from the Parallel Programming Library. But I'm not sure how to go about it as all of the "Future" examples only cover simple types such as strings, integers etc.

Here's the non-parallel code:

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

Where "xls" is the Excel object and "s" is a memory stream.

How would a "Future" go about this? Would I declare xls as...

xls := IFuture<TsmXLSFile>

Is this correct. If it is then do I need to free it like a normal TsmXLSFile since it's now an interface?

Steve


Solution

  • Declare a field to get hold of that interface:

    FXlsFuture: IFuture<TsmXLSFile>;
    

    Add a method to create that future and another one to handle the loaded file:

    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;
    

    In addition you can query the Status of the future to check if the file is already loaded to avoid blocking.