如果在DelphiXE3中使用BeginThread,则会阻塞该函数。为什么会这样呢?
我试图在下面创建我的问题的最小版本。如果按下按钮btn1,则btn1的标题应改为“nooo”。如果按下btn2,则btn1标题改为“yesss”。
当按下btn1时,我还使用BeginThread启动一个线程,该线程将永远循环。
问题是,btn1.Caption := 'nooo';从BeginThread块开始就没有重新定位。我到达nooo 1. := 'nooo';
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
btn1: TButton;
btn2: TButton;
procedure btn1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
private
function test() : Integer;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function TForm1.test() : Integer;
begin
while True do
begin
Sleep(Random(1000) * 2);
end;
Result := 0;
end;
procedure TForm1.btn1Click(Sender: TObject);
var
id: LongWord;
begin
BeginThread(nil, 0, Pointer(test), nil, 0, id);
btn1.Caption := 'nooo';
end;
procedure TForm1.btn2Click(Sender: TObject);
begin
btn1.Caption := 'yesss';
end;
end.发布于 2017-04-05 19:04:59
表达式Pointer(test)调用test(),然后将结果转换为Pointer。因为test()永远不会返回,所以没有要转换的结果,因此也没有传递给BeginThread()的值。BeginThread()本身不会阻塞;它从一开始就不会被调用。
BeginThread()的第三个参数不是Pointer类型;它的类型是TThreadFunc,它是一个独立(非成员)函数,接收一个Pointer参数并返回一个Integer。您的TForm1.test()方法没有限定,因为它不是一个独立的函数。
使test()成为一个独立的函数,然后直接传递给BeginThread() (没有任何类型转换或@操作符):
function test(param: Pointer): Integer;
begin
while True do
Sleep(Random(1000) * 2);
Result := 0;
end;
var
id: LongWord;
begin
BeginThread(nil, 0, test, nil, 0, id);
end;https://stackoverflow.com/questions/43239381
复制相似问题