谁帮我看看这个线程的问题在哪?

lostmyway 2003-09-12 04:49:29
unit UTimeDisplay;

interface

uses
Classes, Graphics, ExtCtrls,Controls,SysUtils,Dialogs,StdCtrls;

type
TCurrTimeDisplay= Class(TThread)
Private
aTimer:TTimer;
aLabel:TLabel;
protected
procedure Execute; override;
procedure DoTerminate;override;
Public
Constructor Create(var TmShowLbl:TLabel);
procedure TimerTimer(Sender:TObject);
end;

implementation

Constructor TCurrTimeDisplay.Create(Var TmShowLbl:TLabel);
begin
//Priority:=tpHigher;
FreeOnTerminate:=True;
aLabel:=TmShowLbl;
aTimer:=TTimer.Create(nil);
with aTimer do
begin
Interval:=1000;
OnTimer:=TimerTimer;
end;
inherited Create(False);
end;

Procedure TCurrTimeDisplay.Execute;
begin
TimerTimer(aTimer);
end;

procedure TCurrTimeDisplay.TimerTimer(Sender:TObject);
begin
aLabel.Caption:=TimeToStr(Time);
aLabel.Refresh;
aTimer.Enabled:=True;
end;

Procedure TCurrTimeDisplay.DoTerminate;
begin
if aTimer<>nil then
aTimer.Free;
end;

现在问题是使用这个线层的程序 只要lose focus(鼠标点到程序外面)就出现“read voliation 0×00000...”错误

怎么控制线程的结束 我不会。

同时还有个问题,我这样写主线层上的赋给“Var TmShowLbl:TLabel”的label 并不会一秒一秒变化 而是就第一次执行的时间 :(
...全文
52 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
lostmyway 2003-09-14
  • 打赏
  • 举报
回复
谢谢各位
xiaoxiao_8 2003-09-14
  • 打赏
  • 举报
回复
timer本身就是一个线程,没必要这样做。
lxpbuaa 2003-09-13
  • 打赏
  • 举报
回复
你这个程序问题比较多。
大的有:
1、
Procedure TCurrTimeDisplay.Execute;
begin
TimerTimer(aTimer); //此句执行完毕后,线程就要销毁了,也就是执行DoTerminate,所以“label 并不会一秒一秒变化 而是就第一次执行的时间”
end;
2、TCurrTimeDisplay.TimerTimer中对共享资源aLabel直接操作,这是不安全的,应该放在TThread.Synchronize中。
其他有:
1、Constructor Create(var TmShowLbl:TLabel);中没必要引用传递TmShowLbl,因为TLabel本身就是指针,宜改为:
Constructor Create(TmShowLbl:TLabel);
2、TCurrTimeDisplay.DoTerminate;中应该集成父类的方法。

“怎么控制线程的结束 我不会”,你这个线程根本就不好控制什么时候结束,原因是根本就不应该在线程中使用TTimer。线程结束是在Execute中控制的,如果你一定要采用现在的设计方式,那么应该加一个控制变量,在Execute中判断该变量的值从而控制Timer.Enabled。

—————————————————————————————————
宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
—————————————————————————————————
aiirii 2003-09-13
  • 打赏
  • 举报
回复
問題很多,建議全部重新設計過!
hkbarton 2003-09-13
  • 打赏
  • 举报
回复
看你的这个程序好象就是要一个显示时间的label,就向要一个表一样,完全没有必要用多线程啊,只用timer就可以办到了
hkbarton 2003-09-13
  • 打赏
  • 举报
回复
你没有使用Synchronize对VCL进行同步访问啊,的确问题比较多

1,183

社区成员

发帖
与我相关
我的任务
社区描述
Delphi Windows SDK/API
社区管理员
  • Windows SDK/API社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧