Delphi 2006 - 优雅地终止线程并仍然触发 OnTerminate 处理程序的最佳方法是什么?
我有一个线程有时会由于永远不会返回的 DLL 调用而冻结(我怀疑)。在一般情况下,当您调用像 Indy 这样的阻塞例程时,是否有一种方法可以通过触发线程 OnTerminate 处理程序来从中恢复?如果我调用 TerminateThread 会发生这种情况吗?
I have a thread that sometimes freezes (I suspect) due to a DLL call that never returns. In the general case, where you have calls to blocking routines like Indy, is there a way of recovering from this in such a way that the thread OnTerminate handler fires? Will this happen if I call TerminateThread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
TerminateThread()
是立即强力终止。它不会让OnTerinaate
事件触发。OnTerminate
可以触发的唯一方法是线程的Execute()
方法通过正常方式退出,无论是优雅地还是通过引发未捕获的异常(这将设置线程的 < code>FatalExpection 属性)。特别是在 Indy 的情况下,可以通过断开套接字与另一个线程的上下文的连接来中止阻塞套接字操作。对于阻塞 DLL 函数来说,这通常是不可能的,除非它们在 API 中公开了此类功能。
TerminateThread()
is an immediate brute-force termination. It will NOT let theOnTerminaate
event fire. The only wayOnTerminate
can fire is if the thread'sExecute()
method exits through normal means, whether that be gracefully or by raising an uncaught exception (which will set the thread'sFatalExpection
property).In the case of Indy specifically, a blocking socket operation can be aborted by disconnecting the socket from the context of another thread. That is not usually possible with blocking DLL functions, unless they expose that kind of functionality in their API.