在formmain创建多线程正常,
在groupForm创建多线程报错,
groupForm := TFormGroup.Create(self);
groupForm.showModal;
FreeAndNil(groupForm); 要把groupForm传进多线程才行,但是感觉有问题,是这样操作的吗? constructor Create(vForm:TFormGroup);
在groupForm创建多线程报错,
groupForm := TFormGroup.Create(self);
groupForm.showModal;
FreeAndNil(groupForm); 要把groupForm传进多线程才行,但是感觉有问题,是这样操作的吗? constructor Create(vForm:TFormGroup);
要注意的就是访问vcl,会不会是线程未结束时,窗体已经关闭了,这就会报错了
我在主窗体FormMain使用同样的多线程代码没问题但是在
FormMain的子窗体FormGroup 使用多线程却提示出错,
FormGroup不是自动创建的 是通过groupForm.showModal手动创建的
Form1unit Unit1;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;implementation{$R *.dfm}
uses Unit2;
procedure TForm1.Button1Click(Sender: TObject);
var
vForm:TForm2;
begin
vForm := TForm2.Create(Application);
vForm.showModal;
FreeAndNil(vForm);
end;end.Form2:
unit Unit2;interfaceuses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;type
TForm2 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form2: TForm2;implementation{$R *.dfm}
uses uTestThread;
procedure TForm2.Button1Click(Sender: TObject);
var
thread1:TTestThread;
begin
thread1:=TTestThread.Create(true);
thread1.Resume;
end;end.
线程代码:
unit uTestThread;interfaceuses
Classes,Windows,SysUtils;type
TTestThread = class(TThread)
private
protected
procedure Execute; override;
end;implementation
uses Unit1,Unit2;procedure TTestThread.Execute;
var
i:Integer;
begin
for i:=1 to 100 do
begin
if Terminated then Break;
Sleep(10);
Form2.Caption:=inttostr(i); //这边改成Form1.Caption:=inttostr(i);的话 代码正常
end;
end;
end.上面的代码没有反应Form2.Caption:=inttostr(i); 这边改成Form1.Caption:=inttostr(i);的话 代码运行正常
我把form2当作参数传进线程,也不行啊
procedure TForm2.Button1Click(Sender: TObject);
var
thread1:TTestThread;
begin
thread1:=TTestThread.Create(self);
thread1.Resume;
end;TTestThread构造函数
constructor Create(vForm:TForm2);
constructor Create(vForm:TForm2);并在TTestThread中用一个成员保存vForm的值,调用时用vForm.Caption:=inttostr(i); 而不是Form2.Caption:=inttostr(i); 这样就行了