我的程序中有一段代码要用线程执行,然后这段代码执行完毕后需要继续执行下面的代码。请问怎样控制,才可以让线程内的程序执行完毕后才接着执行下面的代码呢?
例如
  if not FileExists(sZipFile) then
  begin
    ExportThread := TExportThread.Create(False,Self);
  end;  //执行完这个线程之后才需要执行下面的语句  New(pCIPoint);//为pCIPoint分配空间
  pCIPoint^.ClientIP := Socket.RemoteAddress;
  pCIPoint^.Status := '下载...';
  pCIPoint^.TransFile := 'Backup'+sTemp+'.zip';
  pCIPoint^.fsSend :=TFileStream.Create(sZipFile, fmShareDenyWrite);
  pCIPoint^.Size := IntToStr(TFileStream(pCIPoint^.fsSend).size);
  pCIPoint^.TransSize := '0';按我写的话,程序是在线程执行的同时又执行下面的代码了。菜鸟问题,希望大虾们不吝赐教,谢谢,谢谢。

解决方案 »

  1.   

    好像有个函数叫WaitSingleObject可以等待线程结束
      

  2.   

    WaitSingleObject?
    我在Delphi的帮助文件中找不到这个函数啊
    我用的是Delphi5能不能具体说下用法?谢谢,谢谢
      

  3.   

    等待线程结束用TThread的WaitFor方法即可  if not FileExists(sZipFile) then
      begin
        ExportThread := TExportThread.Create(False,Self);
        ExportThread.waitfor(); //这样即可;
      end; ...这样写,有需要注意的地方,在线帮助中这么写:
    WaitFor doesn't return until the thread terminates, so the thread must exit either by finishing the Execute method or by exiting when the Terminated property is true.即Execute 函数能执行完毕,没有死循环,否则主线程的waitfor将一直不返回;
      

  4.   

    即Execute 函数能执行完毕,没有死循环,否则主线程的waitfor将一直不返回;那请问,线程能执行完毕 的标准是什么?是不是要明确的写Termanite?
      

  5.   

    >>那请问,线程能执行完毕 的标准是什么?>>是不是要明确的写Termanite?没有所谓的标准,只要是Execute这个函数执行完了,线程也就结束了。如,最简单的例子如下:
    procedure TMyThread.Execute;
    begin
      try
        while (not Terminated) do
        begin
           ...
        end;
      finally
      end;
    end;可以简单把把线程想像为一个函数,如上面,当while循环退出了,函数执行完了,线程的代码也就终止运行了;但是,
    线程终止了,并一定就释放了TThread的资源;
    只有当FreeOnTerminate为true时,才会自动释放资源,
    否则就要主线程中用MyThread.Free来主动释放资源
    >>是不是要明确的写Termanite?
    这个要看你的线程是怎么写的,
    Termanite方法其实就是设置 Terminated 属性为true;所以,当主线程中,调用
    MyThread.Termanite;则线程中的while循环,也就要退出了,线程也就要结束了。
    但如果你写的线程,没有类似的while循环,也就无所谓调不调用Termanite了
      

  6.   

    if not FileExists(sZipFile) then
      begin
        ExportThread := TExportThread.Create(False,Self);
        //加上下面这句,Myprocedure是一个过程,自己取名。
        //把要在线程执行后执行的语句写在这个过程里面。
        ExportThread.OnTerminate := Myprocedure;
      end;procedure TForm1.Myprocedure(Sender: Object);
    begin
      //执行完这个线程之后才需要执行下面的语句  New(pCIPoint);//为pCIPoint分配空间
      pCIPoint^.ClientIP := Socket.RemoteAddress;
      pCIPoint^.Status := '下载...';
      pCIPoint^.TransFile := 'Backup'+sTemp+'.zip';
      pCIPoint^.fsSend :=TFileStream.Create(sZipFile, fmShareDenyWrite);
      pCIPoint^.Size := IntToStr(TFileStream(pCIPoint^.fsSend).size);
      pCIPoint^.TransSize := '0';
    end;