手动超时C#线程 [英] Manually Timing out a C# Thread
问题描述
我需要为长时间运行的线程添加超时.我们遇到了一些外部问题,有时可能导致该线程无限期地挂在特定的代码行上.为了使我们的过程更加健壮,我们希望检测到该线程不再正在主动运行/轮询并中止该线程.这样我们就可以清理资源并重新启动线程.
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?
推荐答案
您需要两件事:
- 其他一些可以进行监视和中止的线程(您的监视"线程)
- 一些机制来检查可疑线程是否仍在工作
在最简单的版本中,您的可疑线程以可靠的频率更新当前时间的共享静态变量.如何适应线程的控制流由您决定(这是最困难的部分-通常,您会用另一个线程来做这种事情).然后只需唤醒第二个线程,并经常检查一次即可.如果不是最近,请中止线程.
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.
//suspect thread
foreach(var thing in whatever)
{
//do some stuff
SomeClass.StaticVariable = DateTime.Now;
}
//monitor thread
while(shouldStillBeWorking)
{
Thread.Sleep(TimeSpan.FromMinutes(10));
if (DateTime.Now.Subtract(TimeSpan.FromMinutes(15) < SomeClass.StaticVariable)
suspectThread.Abort()
}
这篇关于手动超时C#线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!