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

标签 delphi

我正在创建一个单元,在其中使用 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/

相关文章:

arrays - Delphi如何解析带有指针(无类型)参数的重载函数?

delphi - 我应该如何调整我的代码以实现 TBytes 和 TIdBytes 之间的兼容性?

delphi - JVCL安装

delphi - 如何调用克隆的对象

delphi - 当操作管理器位于数据模块中时,键盘快捷键未捕获?

delphi - Delphi 是否有通用的 "Object Pool"实现?

c# - 是否可以将此 Delphi 函数转换为 C# 方法?如何?

Delphi 获取文件位置

delphi - DScintilla 是否有语法突出显示的示例?

javascript - Smart Mobile Studio 中的正则表达式