TXMLDocumentAsyncLoadState (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example uses the AsyncLoadState property. To illustrate this, an XML file is loaded in a separate thread. The AsyncLoadState property is read from the main thread until the XML file is fully parsed.

Code

type
  TThreadLoad = class(TThread)
  private
    procedure Execute; override;
  public
    FDocument: IXMLDocument;
  end;

procedure TThreadLoad.Execute;
var
  LResult: HRESULT;
begin
  try
    LResult := CoInitializeEx(nil, COINIT_MULTITHREADED);

    if not((LResult = S_OK) or (LResult = S_FALSE)) then
    begin
      Writeln('Failed to initialize COM library.');
      Exit;
    end;

    try
      FDocument.LoadFromFile(SrcPath);
    except
      on E: Exception do
        Writeln('Exception inside thread.' + sLineBreak + E.Message);
    end;
  finally
    CoUnInitialize;
  end;
end;

procedure Test_AsyncLoad;
const
  CStateComplete = 4;
var
  po: TParseOption;
  LThread: TThreadLoad;
  LDocument: IXMLDocument;
  LState: Integer;
begin
  LThread := TThreadLoad.Create(True);
  LThread.FDocument := TXMLDocument.Create(nil);
  LDocument := LThread.FDocument;
  LDocument.ParseOptions := [poAsyncLoad];

  LThread.Priority := tpIdle;
  LThread.Start; { The thread will start loading the document from file. }

  try
    repeat
      LState := LDocument.AsyncLoadState;
      Writeln('Async load state is ' + IntToStr(LState));
    until LState = CStateComplete;
  except
    on E: Exception do
      Writeln('Exception inside thread.' + sLineBreak + E.Message);
  end;
end;

Uses