Einzelnen Beitrag anzeigen

TiGü

Registriert seit: 6. Apr 2011
Ort: Berlin
3.070 Beiträge
 
Delphi 10.4 Sydney
 
#6

AW: Sequentielle Abarbeitung mit Threads - Anregungen erwünscht

  Alt 7. Dez 2017, 10:44
Delphi-Quellcode:
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}


uses
  System.SysUtils,
  System.Threading;

type
  IResponse = interface
    ['{E705E40C-9BC2-41EE-AE4B-2E1D514395E9}']
    function HasMoreData: Boolean;
  end;

  TResponse = class(TInterfacedObject, IResponse)
  private
    class var
      FCounter: Integer;
  public
    function HasMoreData: Boolean;
  end;

  TMyClass = class
    procedure GetData;
    function GetDataFromServer: IResponse;
    procedure DoSomeGreatWork;
  end;

procedure TMyClass.DoSomeGreatWork;
begin
  Writeln('Make Work Great Again!');
end;

procedure TMyClass.GetData;
var
  MoreData: Boolean;

  procedure ReceiveData;
  var
    Response: IResponse;
  begin
    Response := GetDataFromServer;
    DoSomeGreatWork;
    MoreData := Response.HasMoreData;
  end;

begin
  repeat
    ReceiveData;
    Writeln('HasMoreData: ', MoreData);
  until not MoreData;

  Writeln('Fix und fertig!');
end;

function TMyClass.GetDataFromServer: IResponse;
begin
  Result := TResponse.Create;
  Sleep(50);
end;

function TResponse.HasMoreData: Boolean;
begin
  Result := True;
  Inc(FCounter);
  if FCounter = 100 then
    Result := False;
end;

procedure Main;
begin
  TTask.Run(
    procedure
    var
      MyObject: TMyClass;
    begin
      MyObject := TMyClass.Create;
      try
        MyObject.GetData;
      finally
        MyObject.Free;
      end
    end);
end;

begin
  try
    Main;
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
  Mit Zitat antworten Zitat