unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TTestThread=class(TThread)
procedure Execute;override;
end;
var
Form1: TForm1;implementation{$R *.dfm}
procedure TTestThread.Execute;
begin
FreeOnTerminate:=True;
ShowMessage('已经激活');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Test:TTestThread;
begin
Test:=TTestThread.Create(false);
end;end.单击按钮,有时候会弹出对话框,有时候搞什么乱七八糟的东西,为什么?
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TTestThread=class(TThread)
procedure Execute;override;
end;
var
Form1: TForm1;implementation{$R *.dfm}
procedure TTestThread.Execute;
begin
FreeOnTerminate:=True;
ShowMessage('已经激活');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Test:TTestThread;
begin
Test:=TTestThread.Create(false);
end;end.单击按钮,有时候会弹出对话框,有时候搞什么乱七八糟的东西,为什么?
ShowMessage在线程中直接用是不安全的。正确的做法是线程需要ShowMessage时,用SendMessage发送消息给主窗口,然后在主窗口的消息处理函数中ShowMessage
type
TTestThread=class(TThread)
procedure Execute;override;
procedure a;
end;
var
Form1: TForm1;implementation{$R *.dfm}
procedure TTestThread.a;
begin
ShowMessage('已经激活');
end;
procedure TTestThread.Execute;
begin
inherited;
FreeOnTerminate:=True;
Synchronize(a)
end;