如何在 Delphi Object Pascal 中停止线程

问题描述 投票:0回答:1

我有一个按钮1和一个标签1。单击按钮 1 时,标签 1 开始在其自己的线程上计数。

问题是当单击button2时我无法停止线程。

这是我正在使用的代码:

unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.Controls.Presentation, FMX.StdCtrls, System.SyncObjs;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private

  public

  end;



{ TMyThread is the class that will handle background work for Label1 }
MyThread1 = class(TThread)
private
    count: Integer;
    msg: string;
     stopThread:boolean;
protected
    procedure Execute; override;
    procedure UpdateUI;
public
    constructor Create;
end;





var
  Form1: TForm1;

implementation

{$R *.fmx}




{ MyThread Constructor }
constructor MyThread1.Create;
begin
  inherited Create(False); // False means it will start right away
  FreeOnTerminate := True; // Free memory when finished
end;




{ Worker Thread for Label1 }
procedure MyThread1.Execute;
var
  i: Integer;
begin
  for i := 1 to 1000 do
  begin

  //Check to see if the was terminated. If so, then exit the for loop.
    if Terminated then
        Exit;

    Sleep(10); // Simulate work (1 second per iteration)
    msg := '# ' + IntToStr(i);
    Synchronize(UpdateUI); // Update UI safely from the main thread
  end;

  Synchronize(UpdateUI);
end;



{ Update the UI for Label1 }
procedure MyThread1.UpdateUI;
begin
  Inc(count);
  Form1.Label1.Text := msg;

  //WHen finished:
  if (count = 1000) then
  begin
     ShowMessage('Thread 1 Finished!');
  end;

end;




{Start the thread when button1 is clicked}
procedure TForm1.Button1Click(Sender: TObject);

begin

  MyThread1.Create; // Create and start the first thread for Label1

end;



procedure TForm1.Button2Click(Sender: TObject);
    //Procedure to stop the MyThread1 thread goes here.

begin


end;

end.

我试图停止线程,但它没有停止。

我无法终止该线程的具体问题可能是什么?

delphi delphi-7 pascal freepascal lazarus
1个回答
0
投票

摆脱

stopThread
成员,你没有使用它。您的线程代码正在查看线程的
Terminated
属性,因此调用线程的
Terminate()
方法。

© www.soinside.com 2019 - 2024. All rights reserved.