作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个单元,在其中使用 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/
StateOfJS 已发布了 2020年的 JavaScript 现状调查报告。今年的 JavaScript 现状调查是该调查的第五版,覆盖了来自 137 个国家的 23,765 位受访者;其中,大
我是一名优秀的程序员,十分优秀!