问题描述
- delphi线程问题 delphi 程序里我写了一个方法
- delphi 程序里我写了一个方法,方法里面的算法比较复杂,计算起来时间比较长,我想把这个方法单独放到一个线程里去执行,请问是怎么写?一点头绪没有啊,谢谢
解决方案
unit Unit1;
interface
uses
Windows Messages SysUtils Variants Classes Graphics Controls Forms
Dialogs StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyThread = class(TThread)
protected
procedure DoWork;
procedure Execute; override;
end;
var
Form1: TForm1;
MyThread: TMyThread;
implementation
{$R *.dfm}
procedure TMyThread.Execute;
begin
//算法比较复杂
while not Terminated do
Synchronize(DoWork);
end;
procedure TMyThread.DoWork;
begin
Form1.CheckBox1.Checked := True;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Button1.Caption = 'Stop' then begin
MyThread.Terminate;
Button1.Caption := 'Start';
Exit;
end;
MyThread:=TMyThread.Create(False);
MyThread.Priority:=tpNormal;
Button1.Caption := 'Stop';
Form1.CheckBox1.Checked := False; // start Thread
end;
end.