gpt4 book ai didi

delphi - 在Delphi的单元中抛出线程

转载 作者:行者123 更新时间:2023-12-02 04:39:35 30 4
gpt4 key购买 nike

我正在创建一个单元,在其中使用 BeginThread 和类中定义的变量抛出一个线程。

代码:

unit practica;

interface

uses Windows;

type
TTest = class
private
public
probando: integer;
procedure iniciar_thread;
procedure load_now;
end;

implementation

procedure TTest.load_now;
begin
Sleep(probando);
end;

procedure TTest.iniciar_thread;
begin
BeginThread(nil, 0, @TTest.load_now, nil, 0, PDWORD(0)^);
end;

end.

表格:

procedure TForm1.testClick(Sender: TObject);
test:TTest;
begin
test := TTest.Create();
test.probando := 1000;
test.iniciar_thread;
end;

编译时没有错误,但是当你运行该函数时,我得到:

Exception EAccessViolation in module test.exe
System Error. Code5
Runtime error 217

当我解决这个问题时?

最佳答案

您不能使用非静态类方法作为BeginThread()的线程过程。看一下BeginThread()的声明:

type
TThreadFunc = function(Parameter: Pointer): Integer;

function BeginThread(SecurityAttributes: Pointer; StackSize: LongWord;
ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord;
var ThreadId: TThreadID): Integer;

正如您所看到的,它需要一个独立的函数,而不是一个类方法。即使确实如此,您的类方法甚至没有正确的签名。

尝试更多类似这样的事情:

unit practica;

interface

type
TTest = class
private
FThread: Integer;
public
probando: integer;
procedure iniciar_thread;
procedure load_now;
end;

implementation

uses
Windows;

procedure TTest.load_now;
begin
Sleep(probando);
end;

function MyThreadFunc(Parameter: Pointer): Integer;
begin
TTest(Parameter).load_now;
end;

procedure TTest.iniciar_thread;
var
ThreadId: TThreadID;
begin
FThread := BeginThread(nil, 0, MyThreadFunc, Self, 0, ThreadId);
end;

end.

并且不要忘记终止线程,CloseHandle()BeginThread() 返回的线程句柄,以及 Free()当您使用完所有内容后,您的 TTest 对象。

通常,您不应直接使用 BeginThread()。您应该从 TThread 派生一个类:

unit practica;

interface

type
TTest = class
public
probando: integer;
procedure iniciar_thread;
end;

implementation

uses
Classes, Windows;

type
TMyThread = class(TThread)
private
FTest: TTest;
protected
procedure Execute; override;
public
constructor Create(ATest: TTest);
end;

constructor TMyThread.Create(ATest: TTest);
begin
inherited Create(False);
FreeOnTerminate := True;
FTest := ATest;
end;

procedure TMyThread.Execute;
begin
Sleep(FTest.probando);
end;

procedure TTest.iniciar_thread;
begin
TMyThread.Create(Self);
end;

end.

关于delphi - 在Delphi的单元中抛出线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074056/

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