请问如何终止一个正在执行的线程?我用terminate不行,代码如下:
constructor TMyThread.create(MyEdit1: tedit);
begin
  inherited create(false);
  MyEdit := MyEdit1;
  FreeOnTerminate := true;
end;procedure TMyThread.Show;
begin
  MyEdit.Text := inttostr(count);
end;procedure TMyThread.Execute;
var
  i: integer;
begin
  for i := 0 to 100000 do
  begin
    count := i;
    Synchronize(show);
  end;
end;procedure TForm1.Button1Click(Sender: TObject);   ////开始
begin
  mythread := TMyThread(edit1);
end;procedure TForm1.Button2Click(Sender: TObject);   ////终止
begin
  mythread.terminate;
  mythread.free;
end;当我点击终止按钮时,文本框中的数据停止增加,但是过会便报错,而且文本框中的数据
立刻变成了100000。
请问如何实现,当我按终止时,文本框中的数据永远停止增加。

解决方案 »

  1.   

    不是:mythread.terminate,用mythread.DoTerminate;
      

  2.   

    调用terminate只是把一个termianted属性设置为true,并没有强制终止线程,是否中止要靠线程不断地查看terminated,如果为true就主动退出。另外你在主线程调用了mythread.free;但你在线程中由使用了Synchronize(show);这就是导致你出错的原因,用使tthread的destroy析构函数有下面一段代码
      if not FFinished and not Suspended then
      begin
        Terminate;
        WaitFor;
      end;
    主要是waitfor的问题,waritfor和Synchronize函数不能同时使用。
    你的代码有两处要改动,一是execute函数的循环体增加一句
    if Terminated then exit;
    另外把响应button2的click事件中的函数中mythread.free;去掉
      

  3.   

    在.Execute函数中适当的地方(可能不止一个地方)加上:
    if terminated then Exit;