procedure mythread.execute
var
  timer:ttimer;
  .......
begin
  timer:=ttimer.create(self);
  .....
end;
  当使用 create(self)时,出现编译错误:TComponent incompatible type TComponentand mythread.这个问题如何解决?
   在线程中如何动态创建timer?

解决方案 »

  1.   

    你是在线程内调用,所以Self是指的TThread的派生类TMythread,而构造函数的参数应该是一TComponent的派生类,需要注意的是TThread是直接从TObject继承而来的,所以显然TMyThread和TComponent不兼容,你应该用Create(Application)
      

  2.   

    可以直接用Create(nil)
    这种用法感觉不是很好……
      

  3.   

    最好的用法是unit Unit2;interfaceuses
      Classes, extctrls;type
      aaa = class(TThread)
      private
        FTimer:TTimer;
      protected
        procedure Execute; override;
      public
        Constructor Create;
        Destructor Destroy; override;
      end;implementationconstructor aaa.Create;
    begin
      inherited Create(False);
      FTimer:=TTimer.Create(nil);
    end;destructor aaa.Destroy;
    begin
      inherited;
      FTimer.Free;
    end;procedure aaa.Execute;
    begin
      { Place thread code here }
    end;end.
      

  4.   

    谢谢各位!新问题又来了.为什么我的定时器没有反应?源码如下:
     
    procedure Tmythread.clientexecute;
    var
        timer:ttimer;
       ........
    begin
      Timer:=TTimer.Create(application);
      Timer.Interval :=1000;
      Timer.OnTimer :=TimerTimer;
      timer.Enabled :=true;
      while (not Terminated)  do
      begin
       .....
      end;
    end;procedure TMythread.TimerTimer(Sender: TObject);
    begin
    Synchronize(disp_add);
    end;这些源码在VCL主线程中执行没问题,而在线程中执行没反应,为什么?
      

  5.   

    我想是因为事件的所有者是TMythread的原因,你可以把TimerTimer事件写成主窗体的事件,即
      procedure    TMainForm.TimerTimer(Sender:TObject);
      begin
      end;
      

  6.   

    但是我想用定时器定时向客户端发送数据,如果把timer写成窗体事件,就难以控制了.有什么好的解决方法吗?
      

  7.   

    建议您访问www.etechbase.net/tech,里面有很多资料,也许可以解决您的问题。
    访问http://168.168.18.11:81/etechbase/advsearch.php将您的问题输入查询内容框,选择不同的精确程度,即可以找到你所需要的答案。效果还是可以的。