各位好,最近在学习Delphi时,想线程练手程序,碰到以下问题:
思路: 点击Form上的Button,线程开始执行;线程在运行过程中,让Form上的Label不断更新。
线程类:
TMyThread = class(TThread)
public
constructor Create(var lable:TLabel);
protected
procedure Execute;override;
private
ShowHint : TLabel;
Terminate : Boolean;constructor TMyThread.Create(var lable:TLabel);
begin
ShowHint := lable; //此处抛出异常
Terminate := True;
end;……
然后再Button点击事件里,启动线程
procedure TForm1.btn1Click(Sender: TObject);
begin
ThreadRun.Create(lbl1); //创建、启动线程
end;……在Delphi里面,TLabel对象作为参数传递给线程,然后在线程里面再使用,这样可行吗?
思路: 点击Form上的Button,线程开始执行;线程在运行过程中,让Form上的Label不断更新。
线程类:
TMyThread = class(TThread)
public
constructor Create(var lable:TLabel);
protected
procedure Execute;override;
private
ShowHint : TLabel;
Terminate : Boolean;constructor TMyThread.Create(var lable:TLabel);
begin
ShowHint := lable; //此处抛出异常
Terminate := True;
end;……
然后再Button点击事件里,启动线程
procedure TForm1.btn1Click(Sender: TObject);
begin
ThreadRun.Create(lbl1); //创建、启动线程
end;……在Delphi里面,TLabel对象作为参数传递给线程,然后在线程里面再使用,这样可行吗?
改为
constructor TMyThread.Create(lable:TLabel);
inherited Create(False);2.可行,但是要同步到主线程:
TMyThread = class(TThread)
...
procedure DoIt;
end;procedure TMyThread.DoIt;
begin
ShowMessage(lable.Caption)
end;procedure TMyThread.Execute;
begin
inherited;
...
Synchronize(DoIt);
...
end;另外,ThreadRun.Create(lbl1);中的ThreadRun是啥?
var
Form1: TForm1;
ThreadRun : TMyThread;
……lbl1是TForm1里面TLabel控件
TForm1 = class(TForm)
btn1: TButton;
btn2: TButton;
lbl1: TLabel;
procedure btn1Click(Sender: TObject);
……现在的问题是:在TMyThread里面定义的 ShowHint : TLabel; 这个变量如何和TForm1里面的TLabel关联起来?然后再线程里面就可以使用了
ThreadRun:=TMyThread.Create(lbl1); //而不是ThreadRun.Createconstructor TMyThread.Create(Lable:TLabel);
begin
ShowHint := lable; inherited Create(False);
end;