Einzelnen Beitrag anzeigen

Klaus01

Registriert seit: 30. Nov 2005
Ort: München
5.771 Beiträge
 
Delphi 10.4 Sydney
 
#4

AW: mehrere Threads sauber beenden

  Alt 10. Jan 2011, 11:18
Hallo,

mal ein kleines Konstrukt:

Delphi-Quellcode:
constructor TTestThread.create;
begin
  inherited create(false);
  freeOnTerminate := true;
end;

procedure TTestThread.execute;
begin
  while not terminated do
    begin
      sleep(100);
    end;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  ThreadList.Add(TTestThread.Create)
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  showMessage(intToStr(threadList.count));
  threadList.free;
end;

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
  i : Byte;
begin
  canClose := false;
  while ThreadList.Count > 0 do
    begin
      for i:= ThreadList.count -1 downto 0 do
        begin
          (ThreadList[i] as TTestThread).terminate;
          while not (ThreadList[i] as TTestThread).Terminated do
            begin
              sleep(200);
            end;
           ThreadList.Delete(i);
        end;
    end;
  canClose := true;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ThreadList := TObjectList.Create(false);
end;
Grüße
Klaus
Klaus
  Mit Zitat antworten Zitat