手动使 C# 线程超时
我需要为长时间运行的线程添加超时。我们遇到一些外部问题,有时会导致该线程无限期地挂在某一行代码处。为了使我们的进程更加健壮,我们希望检测线程不再主动运行/轮询并中止该线程。这将使我们清理资源并重新启动线程。
添加此功能的首选方法是什么?
I have a need to add a timeout to a long running thread. We're having some external issues which can sometimes cause that thread to hang at a certain line of code indefinitely. To make our process more robust, we would like to detect that the thread is no longer actively running/polling and abort the thread. This would let us clean up the resources and restart the thread.
What would be the preferred method of adding this functionality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首选方法是在其自己的进程中运行不可靠子系统,而不是在其自己的线程中。这样,当它表现不佳时,您可以破坏整个进程,并让操作系统清理它留下的任何可怕的混乱。杀死进程中运行不可靠代码的线程可能会对您的代码产生各种令人讨厌的副作用,因为操作系统无法知道哪些资源属于行为不良的线程以及您仍在使用哪些资源。
长话短说:不要与您无法控制的代码共享进程。
The preferred method is to run the unreliable subsystem in its own process, not its own thread. That way when it behaves badly you can destroy the entire process and have the operating system clean up whatever horrid mess it leaves behind. Killing a thread that is running unreliable code in your process can have all kinds of nasty side effects on your code because the operating system has no way of knowing what resources belong to the ill-behaved thread and which ones you're still using.
Long story short: do not share a process with code you cannot control.
您需要两件事:
在最简单的版本中,您的可疑线程使用当前时间更新共享静态变量可靠的频率。如何适应线程的控制流取决于您(这是困难的部分 - 您通常会使用另一个线程来执行此类操作)。然后唤醒第二个线程并经常检查它。如果不是最近的时间,则中止线程。
You need two things:
In the simplest version your suspect thread updates a shared static variable with the current time with a reliable frequency. How that fits into the control flow of your thread is up to you (This is the hard part - you would normally do that sort of thing with, ahem, another thread). Then just have a second thread wake up and check it every so often. If it's not a recent time, abort the thread.
在主应用程序中启动一个计时器,该计时器会在超时期限过后中止工作线程。使用工作线程中的回调方法来重置计时器。
Start a timer in your main app that aborts the worker thread after your timeout period elapses. Use a callback method from your worker thread to reset the timer.