delphi中终止线程
如何以正确的方式终止线程? 当线程结束时,它仍然在内存中。我正在使用 Delphi 2010(更新 5)。
How can I terminate a thread in a proper way?
When the thread finishes, it is still in memory. I'm using Delphi 2010 (Update 5).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通常描述线程终止问题的方式是强调合作。您不应该终止线程。相反,您应该通知线程您希望它终止。然后,您礼貌地等待,直到它终止。
其原因是显而易见的。只有线程知道如何终止自身。只有线程知道它持有什么锁、需要释放什么资源等。
如果您希望暂停或挂起线程的执行,则适用相同的参数。您应该要求它这样做,然后让线程找到一个安全的方便时刻来这样做。
对于 Delphi
TThread
,请求终止的标准方法是调用Thread.Terminate
。这只不过是在线程对象中设置一个标志。这就是要求。响应由TThread.Execute
内的线程代码发起。那应该定期检查其Termminate
属性的值。当发现这是真的时,它应该退出该函数。当然,任何整理(释放锁、返回资源等)都应该在调用 exit 之前执行。The way I usually describe the issues of thread termination is to stress co-operation. You should not terminate a thread. Instead you should notify the thread that you want it to terminate. You then politely wait until it has terminated.
The reasons for this are manifest. Only the thread knows how to terminate itself. Only the thread knows what locks it holds, what resources it needs to free etc.
The same arguments apply if you wish to pause or suspend a thread's execution. You should ask to it do so and then let the thread find a convenient moment when it is safe to do so.
With a Delphi
TThread
the standard way to request termination is to callThread.Terminate
. This does nothing more than to set a flag in the thread object. That is the request. The response is initiated by the thread code insideTThread.Execute
. That should regularly check the value of itsTerminated
property. When that is found to be true, it should exit from the function. Naturally any tidy up (release locks, return resources etc.) should be performed before calling exit.究竟如何终止一个线程?如果您只是设置终止,这只是在线程内部检查的标志。如果您需要终止执行线程(并且不向 TThread 对象发出需要完成的信号),您可以使用 TerminateThread WinAPI 函数。但您应该注意到,这会导致资源泄漏(如 TerminateThread 文档中的注释所写)。
How exactly do you terminate a thread? If you just set Terminate, this is just a flag checked inside of the thread. If you need to terminate thread of execution (and not signal a TThread object that it needs to finish), you can use TerminateThread WinAPI function. But you should notice that this leads to resource leaks (as written in the comments in documentation for TerminateThread).
这取决于您想用该线程完成什么任务。在我们为您提供帮助之前,您应该提供有关您想要做什么的更多详细信息。
这里有一个关于如何在 Delphi 中使用线程的非常好的教程:
http ://www.eonclash.com/Tutorials/Multithreading/MartinHarvey1.1/Ch1.html
http://docwiki.embarcadero.com/RADStudio/en/Writing_multi-threaded_applications_Index
that depends on what you want to accomplish with that thread. you should provide more details about what you want to do, before we can help you.
here you have a very good tutorial on how to work with threads in Delphi:
http://www.eonclash.com/Tutorials/Multithreading/MartinHarvey1.1/Ch1.html
http://docwiki.embarcadero.com/RADStudio/en/Writing_multi-threaded_applications_Index