gpt4 book ai didi

multithreading - Delphi - 未创建自定义线程

转载 作者:行者123 更新时间:2023-12-03 19:40:15 28 4
gpt4 key购买 nike

我这里有点问题。我有一个继承 TPersistent 类的自定义类,在这个自定义类内部(私有(private)部分),我有一个自定义的 TThread,它具有覆盖的 Execute 方法,每(1000 毫秒)触发一次。一切都很好,直到我将我的 2 个自定义类移动到一个新单元......

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;

上面的代码在主项目单元中工作得很好,但是当我将它移动到一个新单元时,线程代码不再工作,当我尝试释放一个 TMyClass 对象时,我得到一个 AV。我认为线程根本没有被构建,这就是为什么我在尝试释放它时得到一个 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.

单元2:
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.

最佳答案

构造函数TMyClass.Create被宣布为 protected 。这意味着从另一个单元看不到它。因此TMyClass.Create未执行,而是调用 TObject.Create .反过来,这意味着线程永远不会被创建,并且在析构函数运行时会遇到运行时错误,因为 Tnil .

public 声明构造函数能见度。

关于multithreading - Delphi - 未创建自定义线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409840/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com