Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

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

Re: Threads "korrekt" beenden

  Alt 31. Jan 2009, 09:23
Der Einwand ist berechtigt und darum habe ich die KillAllThreads jetzt als class procedure definiert. So kann man aufräumen wann man will, muss aber nicht ...
Delphi-Quellcode:
unit CtrlThread;

interface

uses
  Classes;

type
  TCtrlThread = class( TThread )
  public
    class procedure KillAllThreads;
    constructor Create(CreateSuspended: Boolean);
    destructor Destroy; override;
  end;



implementation

uses
  Contnrs,
  SyncObjs;

var
  CtrlThreadList : TObjectList;
  CS : TCriticalSection;

{ TCtrlThread }

class procedure TCtrlThread.KillAllCtrlThreads;
var
  CTIdx : Integer;
begin
  while
    ( CtrlThreadList.Count > 0 )
  do
    begin

      CS.Enter;
      try

        for
          CTIdx := 0
        to
          CtrlThreadList.Count - 1
        do
          begin
            TCtrlThread( CtrlThreadList.Items[ CTIdx ] ).FreeOnTerminate := True;
            TCtrlThread( CtrlThreadList.Items[ CTIdx ] ).Terminate;
          end;

      finally
        CS.Leave;
      end;

    end;
end;

constructor TCtrlThread.Create(CreateSuspended: Boolean);
begin
  inherited Create( CreateSuspended );

  CS.Enter;
  try
    CtrlThreadList.Add( Self );
  finally
    CS.Leave;
  end;
end;

destructor TCtrlThread.Destroy;
var
  CTIdx : Integer;
begin

  CS.Enter;
  try
    CTIdx := CtrlThreadList.IndexOf( Self );
    if
      ( CTIdx >= 0 )
    then
      CtrlThreadList.Delete( CTIdx );
  finally
    CS.Leave;
  end;

  inherited;
end;

initialization

  CS := TCriticalSection.Create;
  CS.Enter;
  try
    CtrlThreadList := TObjectList.Create;
    CtrlThreadList.OwnsObjects := False;
  finally
    CS.Leave;
  end;

finalization

  TCtrlThread.KillAllThreads;

  CS.Enter;
  try
    CtrlThreadList.Free;
  finally
    CS.Leave;
    try
      CS.Free;
    except
    end;
  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