各位好,最近在学习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对象作为参数传递给线程,然后在线程里面再使用,这样可行吗?

解决方案 »

  1.   

    constructor TMyThread.Create(var lable:TLabel);
    改为
    constructor TMyThread.Create(lable:TLabel);
      

  2.   

    1. create最后应当加上:
    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是啥?
      

  3.   

    线程里使用到Tlabel,需要加同步
      

  4.   

    谢谢楼上的回答。先解释下,ThreadRun是TForm1里面的一个定义的变量。具体如下:
    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关联起来?然后再线程里面就可以使用了
      

  5.   

    搞反了,是这样
    ThreadRun:=TMyThread.Create(lbl1); //而不是ThreadRun.Createconstructor TMyThread.Create(Lable:TLabel);
    begin
      ShowHint := lable;   inherited Create(False);
    end;
      

  6.   

    谢谢楼上几位回答,问题的确是如kaikai_kk和s11ss所说,创建对象实例方式出了问题,改过来就OK了。