对公有参数通过Synchronize处理
unit Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdBaseComponent, IdComponent;
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
TtestThread = class(TThread)
private
recv: string;
procedure HandleInput;
protected
constructor Create;
procedure Execute; override;
end;
var
Form1: TForm1;
HandleThread: TtestThread; // variable (type see above)
implementation
{$R *.dfm}
constructor HandleThread.Create;
begin
freeonterminate:=true;
inherited create(false);
ClientHandleThread.Resume;
end;
procedure HandleThread.HandleInput;
begin
Form1.Memo1.Lines.Add (recv) ;
end;
procedure HandleThread.Execute;
begin
while not Terminated do
begin
if not 条件语句 then
Terminate
else
try
......
Synchronize(HandleInput);//注意这里是对全局变量的异步处理
except
end;
end;
end;
end.
对公有参数通过TCriticalSection处理
unit Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdBaseComponent, IdComponent, SyncObjs;
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
TtestThread = class(TThread)
private
recv: string;
procedure HandleInput;
protected
constructor Create;
procedure Execute; override;
end;
var
Form1: TForm1;
HandleThread: TtestThread; // variable (type see above)
CommLock:TCriticalSection;
implementation
{$R *.dfm}
constructor HandleThread.Create;
begin
freeonterminate:=true;
inherited create(false);
ClientHandleThread.Resume;
end;
procedure HandleThread.HandleInput;
begin
Form1.Memo1.Lines.Add (recv) ;
end;
procedure HandleThread.Execute;
begin
CommLock.Enter;
if not 条件语句 then
Terminate
else
try
......
HandleInput;
except
end;
end;
CommLock.Leave;
end;
end.