您好,请看下免得线程,为何不能终止 ? 谢谢(50分)

  • 主题发起人 主题发起人 新的自我
  • 开始时间 开始时间

新的自我

Unregistered / Unconfirmed
GUEST, unregistred user!
您好 . 下面代码 ,我想实现 : Click Button2 后终止线程,可是实际不行,Button2 点击后,
Self.Caption = 'end' 改变了,但是随后 Button1.Caption 也改变了---- 也就是说
Terminater 没有起作用

倾角为何 ? 怎么处理 ? 谢谢您

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,UThTest;

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;
tt : TTest ;

implementation



{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
tt := TTest.Create(False);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
TTest(tt).Terminate ;
Caption := 'end ' ;
end;
end.
----------------------------------
unit UThTest;

interface

uses
windows,
Classes;

type
TTest = class(TThread)
private
{ Private declarations }
procedure p ;
protected
procedure Execute; override;
end;

implementation

{ Important: Methods and properties of objects in VCL or CLX can only be used
in a method called using Synchronize, for example,

Synchronize(UpdateCaption);

and UpdateCaption could look like,

procedure TTest.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }

{ TTest }

uses Unit1 ;

procedure TTest.Execute;
begin
{ Place thread code here }
while not Terminated do
begin
Sleep(10000) ;
Synchronize(p) ;

end ;
end;

procedure TTest.p ;
begin
Form1.Button1.Caption := 'end' ;
end;

end.

 
TThread.Terminate只是设置一个标志Terminated,不能马上终止线程!

稍微修改一下程序:
if not Terminated then Synchronize(p);

当然,这不能解决马上终止线程的问题。
看看WinAPI TerminateThread, CloseHandle等的相关帮助吧。

 
谢谢,不过还是没有明白

希望指导
 
不明白什么?你想明白什么?
 
我想能够随时终止线程...请问该怎么处理 ?

谢谢
 
把sleep的时间改长一点试试
 
TerminateThread(AThead.Handle);
AThread.Free;
 
接受答案了.
 
后退
顶部