alchemical
alchemical

Reputation: 13995

How do I kill a thread if it takes too long in C#?

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.

Upvotes: 3

Views: 2330

Answers (4)

nik
nik

Reputation: 13468

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.

Upvotes: 0

pavsaund
pavsaund

Reputation: 696

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

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564831

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.

Upvotes: 5

Marc Gravell
Marc Gravell

Reputation: 1064044

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).

Upvotes: 14

Related Questions