Manually Timing out a C# Thread

我的未来我决定 提交于 2019-12-11 03:12:08

问题


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?


回答1:


You need two things:

  1. Some other thread that can do the monitoring and abort (your "monitor" thread)
  2. Some mechanism to see if the suspect thread is still working

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()
}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2187086/manually-timing-out-a-c-sharp-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!