本文介绍了如何在delphi中杀死一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在delphi中,TThread中的一个方法是terminate.似乎子线程不能通过调用终止或释放来杀死另一个线程.例如A(主要形式),B(一个线程单元),C(另一种形式).

In delp a method in TThread is terminate. It seems a subthread can not kill another thread by calling terminate or free.For exampleA(main form), B (a thread unit), C (another form).

B 正在向主窗体和 C 发送数据(通过调用 syncronize),我们尝试在 C 中终止 B,而 B 正在通过调用 B.terminate 执行.但是这个方法不起作用,B 仍在运行,直到它以 execute 方法结束.

B is sending data to main form and C (by calling syncronize), we tried to terminate B within C while B is executing by calling B.terminate. But this method does not work and B is still working until it ends in execute method.

请帮忙.提前致谢.

推荐答案

您必须在线程中检查 Terminate 才能使其工作.例如:

You have to check for Terminate in the thread for this to work. For instance:

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;

有了这个,你可以打电话

With this, you can call

MyThread.Terminate;

它会在处理完另一块工作后立即终止.这被称为优雅的线程终止",因为线程本身有机会完成任何工作并准备终止.

And it'll terminate as soon as it finishes processing another chunk of work. This is called "graceful thread termination" because the thread itself is given a chance to finish any work and prepare for termination.

还有另一种方法,称为强制终止".您可以拨打:

There is another method, called 'forced termination'. You can call:

TerminateThread(MyThread.Handle);

执行此操作时,Windows 会强制停止线程中的任何活动.这不需要检查线程中的已终止",但可能非常危险,因为您在操作过程中杀死了线程.在那之后,您的应用程序可能会崩溃.

When you do this, Windows forcefully stops any activity in the thread. This does not require checking for "Terminated" in the thread, but potentially can be extremely dangerous, because you're killing thread in the middle of operation. Your application might crash after that.

这就是为什么在您完全确定已经弄清楚所有可能的后果之前,您永远不要使用 TerminateThread.目前你没有,所以使用第一种方法.

That's why you never use TerminateThread until you're absolutely sure you have all the possible consequences figured out. Currently you don't, so use the first method.

这篇关于如何在delphi中杀死一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:05
查看更多