Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

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

AW: Prüfen, ob Referenz auf tatsächlich existentes Objekt zeigt

  Alt 6. Okt 2011, 02:09
Ich würde das so umsetzen:

Hier der Erzeuger (die MainForm):
Delphi-Quellcode:
unit view.Server.Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

type
  TForm1 = class( TForm )
    Button1 : TButton;
    procedure Button1Click( Sender : TObject );
    procedure FormCloseQuery( Sender : TObject; var CanClose : Boolean );
  private
    fThreadDemo : TThread;
    fFormCloseRequest : Boolean;
    procedure ThreadDestroy( Sender : TObject );
  public

  end;

var
  Form1 : TForm1;

implementation

uses
  thread.Demo;

{$R *.dfm}

procedure TForm1.Button1Click( Sender : TObject );
begin
  if Assigned( fThreadDemo )
  then
    Exit;

  fThreadDemo := TThreadDemo.Create( True );
  with TThreadDemo( fThreadDemo ) do
    begin
      FreeOnTerminate := True;
      OnDestroy := Self.ThreadDestroy;
      Start;
    end;
end;

procedure TForm1.FormCloseQuery( Sender : TObject; var CanClose : Boolean );
begin
  if Assigned( fThreadDemo )
  then
    begin

      fThreadDemo.Terminate;

      if not fFormCloseRequest
      then
        begin
          fFormCloseRequest := True;
          with TPanel.Create( Self ) do
            begin
              Parent := Self;
              Left := 0;
              Top := 0;
              Width := Self.ClientWidth;
              Height := Self.ClientHeight;
              Caption := 'Wir müssen noch auf den Thread warten!';
            end;
        end;
      CanClose := False;
    end;
end;

procedure TForm1.ThreadDestroy( Sender : TObject );
begin
  if fThreadDemo = Sender
  then
    begin
      fThreadDemo := nil;
      if fFormCloseRequest
      then
        Close;
    end;
end;

end.
und hier der Thread
Delphi-Quellcode:
unit thread.Demo;

interface

uses
  Classes;

type
  TThreadDemo = class( TThread )
  private
    fOnDestroy : TNotifyEvent;
  protected
    procedure Execute; override;
    procedure DoOnDestroy;
  public
    destructor Destroy; override;
    property OnDestroy : TNotifyEvent
      read fOnDestroy
      write fOnDestroy;
  end;

implementation

{ TThreadDemo }

destructor TThreadDemo.Destroy;
begin
  Synchronize( DoOnDestroy );
  inherited;
end;

procedure TThreadDemo.DoOnDestroy;
begin
  if Assigned( OnDestroy )
  then
    OnDestroy( Self );
end;

procedure TThreadDemo.Execute;
begin
  while not Terminated do
    Sleep( 5000 );
end;

end.
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