C# 停止正在运行的线程的安全方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9272332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a safe way to stop a running thread?
提问by aplavin
I have a thread which contains execution of an IronPython script. For some reason I may need to stop this thread at any time, including script execution. How to achieve this? The first idea is Thread.Abort(), but it's known to be evil...
我有一个包含 IronPython 脚本执行的线程。出于某种原因,我可能需要随时停止该线程,包括脚本执行。如何实现这一目标?第一个想法是Thread.Abort(),但众所周知它是邪恶的......
采纳答案by Tudor
Well from you question and subsequent comments I can suggest you two options, with some additional "warnings":
好吧,从你的问题和随后的评论中,我可以建议你两个选项,还有一些额外的“警告”:
If your thread loops executing something on each iteration, you can set a volatile boolean flag such that it exits after finishing the current iteration (pseudocode because I'm not familiar with python):
while shouldExit = false // do stuffThen just set the flag to
truewhen you want the thread to stop and it will stop the next time it checks the condition.If you cannot wait for the iteration to finish and need to stop it immediately, you could go for
Thread.Abort, but make absolutely sure that there is no way you can leave open file handles, sockets, locks or anything else like this in an inconsistent state.
如果您的线程在每次迭代时循环执行某些操作,您可以设置一个 volatile 布尔标志,使其在完成当前迭代后退出(伪代码,因为我不熟悉 python):
while shouldExit = false // do stuff然后只需将标志设置为
true您希望线程停止的时间,它将在下次检查条件时停止。如果您不能等待迭代完成并需要立即停止它,您可以选择
Thread.Abort,但要绝对确保您无法将打开的文件句柄、套接字、锁或任何其他类似的东西保持在不一致的状态。
回答by Eric Lippert
What is a safe way to stop a running thread?
停止正在运行的线程的安全方法是什么?
Put the thread in its own process. When you want it to stop, kill the process.
把线程放在它自己的进程中。当您希望它停止时,请终止进程。
That is the only safeway to kill a thread. Aborting a thread can severely destabilize a process and lose user data. There's no way to avoid the "lose user data" scenario if you really, truly need to be able to kill a thread that could be doing anything. The only way to avoid destabilizing the process that is calling for the abort is to make them different processes entirely.
这是杀死线程的唯一安全方法。中止线程会严重破坏进程的稳定性并丢失用户数据。如果您真的真的需要能够杀死一个可以做任何事情的线程,就没有办法避免“丢失用户数据”的情况。避免破坏要求中止的进程的唯一方法是使它们完全不同。

