views:

329

answers:

4

Duplicate: Killing a thread (C#)


I'm currently passing my thread a threadstart delegate and starting it.

I need a way to kill this thread if I don't receive a response back from it within 3 seconds.

What is the best way to accomplish this? It doesn't have to be with thread/threadstart necessarily, that's just what I've been using so far.

+13  A: 

Killing a thread is always a bad idea, and should be reserved for scenarios where you are already dealing with a sickly process you are about to kill anyway. Do you own the code in the thread? Perhaps put in some state checks and exit cleanly if the flag is set?

If not, and you need the code to work after the abort, a separate process may be safer than a thread-start. At least you won't cripple your own code (with, for example, an unreleased lock, or a hung static constructor / type initializer).

Marc Gravell
+1 Have the thread itself time-out and return instead of killing a healthy thread.
Will Eddins
Chris Brumme has an ***excellent*** post talking about ThreadAbortException: http://blogs.msdn.com/cbrumme/archive/2003/06/23/51482.aspx
280Z28
We don't own the code, the component fails and hangs about 1 in 1000 calls, it will be called 100,000 of times however. This failure rate is considered acceptable--we just need a way to isolate the failure and terminate it...the component is not resource intensive, so even killing it in the middle of something...I'm not sure that would cause many issues.
alchemical
+5  A: 

You can call myThread.Abort, which will (usually) kill the thread, but this is usually a very bad idea.

It's usually a better option to put the abortion logic into the thread itself. If the thread cannot process its work in the 3 second time period, it could abort itself and return the appropriate state. This is a much safer operation, and will be more maintainable in the long run.

Reed Copsey
+1  A: 

Check out this SO-solution using the IAsyncResult.AsyncWaitHandle.WaitOne() method

pavsaund
Implemented this and it seems to work great.
alchemical
A: 

The Thread.Join method is supposed to have a TimeSpan parameter to cause it to exit...
Look for TimeSpan and other synchronization methods on this page.

nik