Thema: Delphi Multithreading GUI

Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

Registriert seit: 5. Jan 2005
Ort: Stadthagen
9.454 Beiträge
 
Delphi 10 Seattle Enterprise
 
#11

AW: Multithreading GUI

  Alt 28. Jan 2014, 15:00
Im Anhang das komplette Projekt und hier nur das Formular. Das ist nix mit massiv paralleler Verarbeitung der Jobs, sondern ein Thread kümmert sich um die Verarbeitung der übergebenen Jobs.

Inklusive der Rückmeldung an das Formular.
Delphi-Quellcode:
unit FormMain;

interface

uses
  ThreadedJobQueue, ProcJob,
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TMainForm = class( TForm )
    Button1 : TButton;
    CheckBox1 : TCheckBox;
    CheckBox2 : TCheckBox;
    CheckBox3 : TCheckBox;
    ListBox1 : TListBox;
    procedure Button1Click( Sender : TObject );
  private
    FJobQueue : TThreadedJobQueue;
    procedure LogStr( const AStr : string );
  public
    procedure AfterConstruction; override;
    procedure BeforeDestruction; override;
  end;

var
  MainForm : TMainForm;

implementation

{$R *.dfm}

procedure TMainForm.AfterConstruction;
begin
  inherited;
  FJobQueue := TThreadedJobQueue.Create;
end;

procedure TMainForm.BeforeDestruction;
begin
  inherited;
  FJobQueue.Free;
end;

procedure TMainForm.Button1Click( Sender : TObject );
begin
  if FJobQueue.IsWorking then
  begin
    LogStr( 'Nicht hektisch werden :o)' );
    Exit;
  end;

  if CheckBox1.Checked then
    FJobQueue.AddJob( TProcJob.Construct(
          procedure
      begin
        LogStr( 'Start 1' );
        Sleep( 1000 );
        LogStr( 'Ende 1' );
      end ) );

  if CheckBox2.Checked then
    FJobQueue.AddJob( TProcJob.Construct(
      procedure
      begin
        LogStr( 'Start 2' );
        Sleep( 1000 );
        LogStr( 'Ende 2' );
      end ) );

  if CheckBox3.Checked then
    FJobQueue.AddJob( TProcJob.Construct(
      procedure
      begin
        LogStr( 'Start 3' );
        Sleep( 1000 );
        LogStr( 'Ende 3' );
      end ) );

  FJobQueue.ProcessJobs;
end;

procedure TMainForm.LogStr( const AStr : string );
begin

  // Diese Methode achtet von selber darauf,
  // dass der eigentlich Zugriff im MainThread-Context erfolgt

  if MainThreadID = GetCurrentThreadId then
  begin

    ListBox1.ItemIndex := ListBox1.Items.Add( AStr );

  end
  else
    TThread.Queue( nil,
      procedure
      begin
        LogStr( AStr );
      end );
end;

end.
Angehängte Dateien
Dateityp: zip dp_178798.zip (2,9 KB, 45x aufgerufen)
Kaum macht man's richtig - schon funktioniert's
Zertifikat: Sir Rufo (Fingerprint: ‎ea 0a 4c 14 0d b6 3a a4 c1 c5 b9 dc 90 9d f0 e9 de 13 da 60)
  Mit Zitat antworten Zitat