Cannot terminate threads

delphi, delphi-xe4, multithreading

Solution

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;

Problem

I use threads in my project. And I wanna kill and terminate a thread immediately. sample: ``` 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; ``` 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? BTW `a.terminate;` didn't work too. Thanks.

Original source