type
TMyThread= class(TThread)
protected
procedure Execute; override;
end;
TMyClass = class(TPersistent)
private
T: TMyThread;
protected
constructor Create;
public
destructor Destroy; override;
end;
implementation
procedure TMyThread.Execute;
begin
while not Self.Terminated do begin
Sleep(1000);
MessageBox(0, 'test', nil, MB_OK)
end;
end;
constructor TMyClass.Create;
begin
inherited Create;
t := TMyThread.Create(False);
end;
destructor TMyClass.Destroy;
begin
t.Terminate;
t.WaitFor;
FreeAndNil(t);
inherited Destroy;
end;
上面的代码在主项目单元中工作得很好,但是当我将它移动到一个新单元时,线程代码不再有效,我得到一个AV,当我尝试释放一个TMyClass对象时。我认为线程根本没有被构造,这就是为什么当我试图释放它时我得到AV ...但为什么呢?代码在哪个单元中无关紧要......
单元1:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, unit2;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
p: TMyClass;
implementation
{$R *.dfm}
procedure TForm1.Button2Click(Sender: TObject);
begin
p.Free; //Getting an AV
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
p := TMyClass.Create;
end;
end.
UNIT2:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TMyThread = class(TThread)
protected
procedure Execute; override;
end;
TMyClass = class(TPersistent)
private
T: TMyThread;
protected
constructor Create;
public
destructor Destroy; override;
end;
implementation
procedure TMyThread.Execute;
begin
while not Self.Terminated do begin
Sleep(1000);
MessageBox(0, 'test', nil, MB_OK)
end;
end;
constructor TMyClass.Create;
begin
inherited Create;
t := TMyThread.Create(False);
end;
destructor TMyClass.Destroy;
begin
t.Terminate;
t.WaitFor;
FreeAndNil(t);
inherited Destroy;
end;
end.
答案 0 :(得分:3)
构造函数TMyClass.Create
被声明为受保护。这意味着从另一个单位看不到它。因此,TMyClass.Create
未执行,而是您正在调用TObject.Create
。反过来,这意味着永远不会创建线程,并且在析构函数运行时遇到运行时错误,因为T
是nil
。
使用public
可见性声明构造函数。