关于线程的Suspend问题(100分)

  • 主题发起人 主题发起人 chyun
  • 开始时间 开始时间
C

chyun

Unregistered / Unconfirmed
GUEST, unregistred user!
各位大侠,我在edit1中显示增加的数字,当按下button1开始,button2暂停,button3继续
但在下面程序中button2和button3不起作用,如果我将Synchronize(draw);改成draw;是可以
的,可是运行不是很流畅,会有停顿。不知如何使用线程的Suspend和Resume才能达到运行很
流畅,并且说停就停,继续就继续。(我试了ResumeThread和SuspendThread也不行)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TDrawThread = class(TThread)
private
protected
procedure Execute;override;
procedure draw;
end;

TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
NewThread : TDrawThread;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
NewThread := TDrawThread.Create(true);
NewThread.Resume;
end;

{ TDrawThread }
procedure TDrawThread.draw;
var
i : integer;
begin
for I:= 0 to 1000000000do
begin
Form1.Edit1.Text := Inttostr(i);
Application.ProcessMessages;
end;
end;

procedure TDrawThread.Execute;
begin
FreeOnTerminate := True;
Synchronize(draw);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
NewThread.Suspend;
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
NewThread.Resume;
end;

end.
 
你的线程函数有问题,做如下修改即可:
type
TDrawThread = class(TThread)
private
I: integer;
protected
procedure Execute;override;
end;

procedure TDrawThread.Execute;
begin
I := 0;
repeat
Inc(I);
Form1.Edit1.Text := Inttostr(i);
until Terminated or (I = 1000000000);
end;
 
TO:thx1180
谢谢:
我是需要Synchronize函数来调用显示数字增加的,不然你这样的修改和我把
Synchronize函数去掉是一样的
 
这样,好像可
FreeOnTerminate := true;
I := 0;
repeat
Inc(I);
Synchronize(draw);
until Terminated or (I = 1000000000);
 
那就这样处理:
把 I 定义为全局变量,把Form1.Edit1.Text := Inttostr(i);
放在Form1的一个
函数(如Draw)中,用Synchronize执行这个函数即可。
区别是:Draw函数在主线程中。
procedure TDrawThread.Execute;
begin
FreeOnTerminate := true;
I := 0;
repeat
Inc(I);
Synchronize(Form1.draw);
until Terminated or (I = 1000000000);
end;
 
你才改的也行。
 
接受答案了.
 
后退
顶部