delphi - terminate all the threads (TThread) on closing application

后端 未结 3 504
无人及你
无人及你 2020-12-29 16:28

My application is a tcp/ip server, with main thread created only once & listening all the time. When new client connects, the main thread creates the new thread of

3条回答
  •  独厮守ぢ
    2020-12-29 17:05

    I use a KillThreadList: TList global. I monitor it in my thread as:

    while (Not Terminated) do
    begin
      inc(Inker);
      if (WaitForSingleObject(FTick, finterval) = WAIT_TIMEOUT) then
      Begin
        if Inker >= 10 then
        Begin
          ProcessTables;
          Inker := 0;
          sleep(1000);
        End;
        if KillThreadList.Contains(ThreadID) = True then Terminate;
      End;
    end;
    

    I also test for the KillThreadList in my processes to let me opt out of them before completion, where safe to do so.

    I pass the OnTerminate event out to the Main thread and remove the ThreadID from the KillList there. I use this model extensively and it has not failed me yet.

    procedure TfrmProcessQualcommLocations.OnTerminateThread;
    var
      ThreadID : Cardinal;
      i : integer;
      aStatusBar :TStatFrame;
    begin
      ThreadID := (Sender as Tthread).ThreadID;
      for i := 0 to StatusBarList.Count -1  do
      Begin
        if StatusBarList.Items[i].ThreadID = ThreadID then
        Begin
          aStatusBar := StatusBarList.Items[i];
          KillThreadList.Extract(ThreadID);
          StatusBarList.Extract(aStatusBar);
          aStatusBar.Free;
          break;
        End;
      End;
    
      self.Refresh;
    end;
    

    In the case above, I am also removing some GUI stuff.

    Hope that helps. SpringerRider

提交回复
热议问题