终止TTask.Run启动的线程
unit Unit15; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Threading, kbmmwprocess, Vcl.StdCtrls, kbmMWClientDataset; type TForm15 = class(TForm) Button1: TButton; kbmMWClientTransactionResolver1: TkbmMWClientTransactionResolver; Button2: TButton; Label1: TLabel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); private FTaskIsRunning: boolean; cnt: Integer; { Private declarations } public { Public declarations } end; var Form15: TForm15; implementation {$R *.dfm} procedure TForm15.Button1Click(Sender: TObject); begin FTaskIsRunning := true; TTask.Run( procedure begin while FTaskIsRunning do begin sleep(99); TThread.Synchronize(nil, procedure begin Label1.Caption := 'Thread is running...' + cnt.ToString; inc(cnt); end); end;//end while. end); end; procedure TForm15.Button2Click(Sender: TObject); begin FTaskIsRunning := false; cnt := 0; end; procedure TForm15.FormCreate(Sender: TObject); begin FTaskIsRunning := false; cnt := 0; end; end.
上面的代码,运行正常,按Button1开启一个线程,Button2终止线程运行。这是一个VCL项目。可以看到用一个私有变量FTaskIsRunning来控件线程中的循环。这个实现是在一个Form中,运行正常,现在换成TFrame中实现,基本上是复制Form中的实现代码,可以忽略不看。
unit Unit16; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,System.Threading; type TFrame16 = class(TFrame) Label1: TLabel; Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private FTaskIsRunning:boolean; cnt:Integer; public { Public declarations } end; implementation {$R *.dfm} procedure TFrame16.Button1Click(Sender: TObject); begin FTaskIsRunning := true; TTask.Run( procedure begin while FTaskIsRunning do begin sleep(99); TThread.Synchronize(nil, procedure begin Label1.Caption := 'Thread is running...' + cnt.ToString; inc(cnt); end); end; end); end; procedure TFrame16.Button2Click(Sender: TObject); begin FTaskIsRunning := false; cnt := 0; end; end.
然后,把Frame放到Form上运行,结果也正常。
将上面的Frame+Form的实现方式,换成FMX项目,在Android,Win32平台运行,也正常。