正确的线程销毁
你好 在我的表单中,我在运行时创建 TFrame。在此框架中,我创建后台线程并在无限循环中执行命令。但是当我销毁这个框架时,我应该销毁这个线程。 我尝试
thread.Suspend;
thread.Terminate;
FreeAndNil(thread);
但得到 AV 和 ThreadError。 我应该如何销毁线程?
Hello
At my form I create TFrame at runtime. At this frame I create background thread with executes commands in endless loop. But when I destroy this frame I should destroy this thread.
I try
thread.Suspend;
thread.Terminate;
FreeAndNil(thread);
but get AV and ThreadError.
How should i destroy thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须确保线程退出其
Execute
方法才能正确终止它。代码可能是这样的:
当你想销毁线程时调用这个:
You must make sure that the thread exits its
Execute
method to terminate it properly.Code could be something like this:
Call this when You want to destroy thread:
执行
thread.Terminate
就足够了。但您可能需要在创建时设置thread.FreeOnTerminate := true
。当然,在线程的紧密循环中(即在 Execute 中),您需要检查线程是否已被请求终止(检查 Termerated 属性) 。如果您发现线程已被请求终止,只需从循环中中断并从
执行
退出即可。It is sufficient to do
thread.Terminate
. But you will probably want to setthread.FreeOnTerminate := true
when it is created.Of course, in the tight loop of your thread (that is, in
Execute
), you need to check if the thread has been requested to terminate (check theTerminated
property). If you find that the thread has been requested to terminate, simply break from the loop and exit fromExecute
.您永远不应该在 tthread 上调用挂起,这样做不安全,并且恢复只能用于启动创建为挂起的线程。
在 Delphi 2010 中,暂停和恢复已被贬值,并引入了启动方法来强化这一点。
如需更完整的说明,请参阅 Codegears 论坛上的主题。
话虽如此,我有两种方法可以终止并释放 tthread。
1:我在创建线程时设置FreeOnTerminate,所以我只是调用。
2:显式释放线程,因为我需要在线程释放之前和终止之后从公共属性读取结果。
在主执行循环中,放入一些异常处理可能是个好主意。
或者您可能想知道为什么线程似乎会终止自身。如果线程设置为 FreeOnTerminate 并且当您尝试释放它时它已经被释放,则这可能会导致 AV。
You should never call suspend on a tthread its not safe to do so and resume should only be used to start a thread that was created suspended.
In Delphi 2010 the suspend and resume where depreciated and the method start was introduced to reinforce this.
For a more complete explanation see this thread at Codegears forums.
having said that there are 2 ways I will terminate and free a tthread.
1: I Set FreeOnTerminate when the thread is created so I just call.
2: Free the thread explicitly, as I need to read a result from a public property before the thread is freed and after it has terminated.
In the main execute loop it may be a good idea to put some exception handling in.
Or you may be left wondering why the thread appears to terminate its self. This may be causing the AV if the thread is set to FreeOnTerminate and it has already been freed when you try to free it.