无法终止线程 [英] Cannot terminate threads

查看:117
本文介绍了无法终止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用线程.我想立即杀死并终止线程.

I use threads in my project. And I wanna kill and terminate a thread immediately.

示例:

    type
      test = class(TThread)
      private
        { Private declarations }
      protected
        procedure Execute; override;
      end;

    var
     Form1: TForm1;
     a:tthread;

    implementation

    {$R *.dfm}

    procedure test.Execute;
    begin

      Synchronize(procedure begin    
          form1.ProgressBar1.position := 0;
          sleep(5000);
          form1.ProgressBar1.position := 100;    
      end
      );

    end;

   procedure TForm1.btn_startClick(Sender: TObject);
   begin
     a:=test.Create(false);
   end;

   procedure TForm1.btn_stopClick(Sender: TObject);
   begin
     terminatethread(a.ThreadID,1);  //Force Terminate
   end;

但是当我单击btn_stop(在单击btn_start之后)时,线程不会停止. 那么如何立即停止该线程?

But when I click on the btn_stop (after clicking on btn_start), the thread won't stop. So how can stop this thread immediately?

顺便说一句a.terminate;也不起作用.

BTW a.terminate; didn't work too.

谢谢.

推荐答案

这是对工作线程的完全滥用.您正在将所有线程的工作委派给主线程,从而使工作线程无用.您本可以使用一个简单的计时器来代替.

This is a complete misuse of a worker thread. You are delegating all of the thread's work to the main thread, rendering the worker thread useless. You could have used a simple timer instead.

正确使用辅助线程看起来像这样:

The correct use of a worker thread would look more like this instead:

type
  test = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
  end;

var
  Form1: TForm1;
  a: test = nil;

implementation

{$R *.dfm}

procedure test.Execute;
var
  I: integer
begin
  Synchronize(
    procedure begin    
      form1.ProgressBar1.Position := 0;
    end
  );

  for I := 1 to 5 do
  begin
    if Terminated then Exit;
    Sleep(1000);
    if Terminated then Exit;
    Synchronize(
      procedure begin
        Form1.ProgressBar1.Position := I * 20;
      end
    );
  end;

  Synchronize(
    procedure begin
      form1.ProgressBar1.Position := 100;    
    end
  );
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  btn_stopClick(nil);
end;

procedure TForm1.btn_startClick(Sender: TObject);
begin
  if a = nil then
    a := test.Create(False);
end;

procedure TForm1.btn_stopClick(Sender: TObject);
begin
  if a = nil then Exit;
  a.Terminate;
  a.WaitFor;
  FreeAndNil(a);
end;

这篇关于无法终止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆