在delphi中,TThread中的方法终止。看来子线程无法通过调用终止或释放来杀死另一个线程。
例如
A(主要形式),B(线程单位),C(其他形式)。
B正在将数据发送到主表单,并且C(通过调用syncronize)发送数据,我们试图在C中终止B,而B通过调用B.terminate执行。但是,此方法不起作用,并且B仍然有效,直到它以execute方法结束。
请帮忙。先感谢您。
最佳答案
您必须在线程中检查Terminate才能起作用。例如:
procedure TMyThread.Execute;
begin
while not Terminated do begin
//Here you do a chunk of your work.
//It's important to have chunks small enough so that "while not Terminated"
//gets checked often enough.
end;
//Here you finalize everything before thread terminates
end;
有了这个,你可以打电话
MyThread.Terminate;
一旦处理完另一部分工作,它将终止。这被称为“优美的线程终止”,因为线程本身有机会完成任何工作并为终止做准备。
还有另一种方法,称为“强制终止”。您可以致电:
TerminateThread(MyThread.Handle);
执行此操作时,Windows将强制停止线程中的任何 Activity 。这不需要检查线程中的“Terminated”,但是可能非常危险,因为您在操作过程中正在杀死线程。之后,您的应用程序可能会崩溃。
这就是为什么直到您完全确定已弄清所有可能的后果后才使用TerminateThread的原因。目前您还没有,所以使用第一种方法。