Reputation: 47749
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?
Upvotes: 2
Views: 395
Reputation: 8531
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.
Upvotes: 0
Reputation: 660118
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.
Upvotes: 6
Reputation:
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.
//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()
}
Upvotes: 2