Thema: Delphi Threads und IdHTTP

Einzelnen Beitrag anzeigen

Benutzerbild von Luckie
Luckie

Registriert seit: 29. Mai 2002
37.621 Beiträge
 
Delphi 2006 Professional
 
#5

AW: Threads und IdHTTP

  Alt 14. Aug 2011, 23:18
Formular:
Delphi-Quellcode:
type
  TForm17 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private

  public
    procedure UpdateLabel(BytesDone: Integer);
  end;

var
  Form17: TForm17;

implementation

{$R *.dfm}

uses
  Unit18; // Thread Unit

procedure TForm17.Button1Click(Sender: TObject);
var
  HTTPThread: TIdHTTPThread;
begin
  HTTPThread := TIdHTTPThread.Create(True); // angehalten erzeugen
  HTTPThread.Url := 'http://www.xxxxxx.pdf';
  HTTPThread.Filename := 'd:\test.pdf';
  HTTPThread.FreeOnTerminate := True;
  HTTPThread.Resume; // ...und starten
end;

procedure TForm17.UpdateLabel(BytesDone: Integer);
begin
  Label1.Caption := IntToStr(BytesDone);
end;
Thread
Delphi-Quellcode:
unit Unit18;

interface

uses
  Classes, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP;

type
  TIdHTTPThread = class(TThread)
  private
    FURL: AnsiString;
    FFilename: AnsiString;
    FBytesDone: Int64;
    IdHTTP: TIdHTTP;
    procedure OnWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer);
    procedure Updatelabel;
  public
    Constructor Create(CreateSuspended: Boolean);
    Destructor Destroy; override;
    property Url: AnsiString read FURL write FUrl;
    property Filename: AnsiString read FFilename write FFilename;
  protected
    procedure Execute; override;
  end;

implementation

{ Wichtig: Methoden und Eigenschaften von Objekten in visuellen Komponenten dürfen
  nur in einer Methode namens Synchronize aufgerufen werden, z.B.

      Synchronize(UpdateCaption);

  und UpdateCaption könnte folgendermaßen aussehen:

    procedure TIdHTTPThread.UpdateCaption;
    begin
      Form1.Caption := 'Aktualisiert in einem Thread';
    end; }


{ TIdHTTPThread }

uses
  Unit17; // Formular Unit

constructor TIdHTTPThread.Create(CreateSuspended: Boolean);
begin
  inherited Create(Suspended);
  IdHTTP := TIdHTTP.Create;
  IdHTTP.OnWork := OnWork;
end;

destructor TIdHTTPThread.Destroy;
begin
  IdHTTP.Free;
  inherited;
end;

procedure TIdHTTPThread.Execute;
var
  DestStream: TFileStream;
begin
  DestStream := TFileStream.Create(Filename, fmCreate);
  try
    IdHTTP.Get(Url, DestStream);
  finally
    DestStream.Free;
  end;
end;

procedure TIdHTTPThread.OnWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer);
begin
  FBytesDone := AWorkCount;
  Synchronize(Updatelabel);
end;

procedure TIdHTTPThread.Updatelabel;
begin
  Form17.UpdateLabel(FBytesDone)
end;

end.
Michael
Ein Teil meines Codes würde euch verunsichern.
  Mit Zitat antworten Zitat