TThread.CreateAnonymousThread() 匿名线程对象的应用

unit Unit1;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,System.SyncObjs;

type
TForm1 = class(TForm)
btn1: TButton;
procedure btn1Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
finish: Boolean;
breaking: Boolean;
public
procedure Myfun;
end;

var
Form1: TForm1;
readwritelock: TCriticalSection;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
begin
finish := False;
breaking := False;
TThread.CreateAnonymousThread(Myfun).Start;
end;

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
readwritelock.Enter;
try
breaking := True;
finally
readwritelock.Leave;
end;
while not finish do
Sleep(10);
end;

procedure TForm1.Myfun;
var
i : Integer;
b: Boolean;
begin
for i := 0 to 5000000 do
begin
readwritelock.Enter;
try
b := breaking;
finally
readwritelock.Leave;
end;
if b then Break;

Self.Canvas.Lock;
Canvas.TextOut(10,10,IntToStr(i));
Self.Canvas.Unlock;
end;
finish := True;
end;

initialization
readwritelock := TCriticalSection.Create;
end.

上一篇:dbrd 8.4.6 源代码编译安装


下一篇:16、编译安装ansible