在多线程程序中,程序要关闭,但此时还有线程正在执行,如何才能实现点关闭时,等到当前所有线程执行完后再关闭程序。以下是我的代码,但这样关闭程序会报内存错误。
FThreadList是TThreadList类型的对象,请各们大侠指点。procedure TFrm_Main.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
  i: integer;
  FList: TList;
  ret: DWORD;
begin
  SendTimer.Enabled := false;
  if FThreadList <> nil then
  begin
    try
      FList := FThreadList.LockList;
      for i := FList.Count - 1 downto 0 do
      begin
        repeat
          //TClientThread(FList.Items[i]).Terminate;
          ret := WaitForSingleObject(Cardinal(FList.Items[i]), 100); //等待
          Application.ProcessMessages;
        until ret <> WAIT_TIMEOUT;
        FList.Remove(FList.Items[i]);
      end;
    finally
      FThreadList.UnlockList;
    end;
    FThreadList.Free;
  end;
  if fDBCommon <> nil then
    fDBCommon.Free;
  CanClose := true;
end;

解决方案 »

  1.   

    athread.FreeOnTerminate:=true;退出时Terminate线程,自动释放,同时线程的Execute消息的循环体中加上 if Terminated then exit;否则无法退出
      

  2.   

    呵呵,楼上讲的差不多了,外部form退出时athread.Terminate;
    你这样一直等到线程完成再退出就有点太霸道了。呵呵
      

  3.   

    同意楼上的。
    在线程的Execute循环体中加上 if Terminated then exit 
    退出窗体时再写上:
      FThreadList.Terminate;
      FThreadList.free;
    但我觉得不一定要写 FThreadList.FreeOnTerminate:=true; 在线程Terminate时自动释放,反正线程Terminate后就关闭窗体了。