views:

145

answers:

3

As we know each timer elapsed method callbacks on a separate thread. Is there a way to abort the timer thread in c#? Suppose a timer thread is blocked in a long running operation. How would a new thread abort the blocked thread? the Thread.CurrentThread points to the calling thread instead of the blocked thread.

A: 

Seems to me the simplest way is to store the thread object before the timer thread does any work with code like this:

timerThread = System.Threading.Thread.CurrentThread;

Then when you need to abort it, call

timerThread.Abort();

Edit: Per comments, I will say that aborting threads is not a good idea. It's better to have them terminate gracefully. I would suggest sending some sort of message to the thread, possibly by simply setting a flag, and having the thread terminate itself when it finds that message.

BlueMonkMN
That's really not a good idea. It will raise a `ThreadAbortException` inside the thread which may or may not be prepared to handle it. Even worse if the thread ends up being a `ThreadPool` thread.
Aaronaught
Right, aborting threads is not a good idea, but that was the question.
BlueMonkMN
System.Threading timers uses the ThreadPool and the ThreadPool re-use threads killing one under it's feet is never a good idea.
VirtualBlackFox
suppose a thread is blocked in a long running operation. How would a new thread abort the blocked thread?
nitroxn
Thread.Abort is the "rudest" way I know to interrupt a thread, so if Abort doesn't stop a blocked thread, I don't know what will.
BlueMonkMN
+2  A: 

Implement your timer as a BackgroundWorker with WorkerSupportsCancellation and check for CancelPending inside your manually written timer?

Oren Mazor
I believe that even if u cancel the background thread worker. it continues processing the working in the background.
nitroxn
It can continue processing. It is up to you to check for CancellationPending in your BackgroundWorker's DoWork method and stop if this is true.
Daniel Rose
Uh. yes. I didn't realize I had to explicitly say that. BackgroundWorker is essentially a Thread object with two benefits: - it lets you request cancellation (externally) and then check if a cancellation was requested (internally) so you can have a clean exit - capture the thread termination event
Oren Mazor
A: 

Aborting threads results in asynchronous exception. So the best way to abort threads is not to abort at all. Instead use mutex and semaphores to signal cancellation and then continuously poll for the cancellation state. if cancel is signaled do nothing.

nitroxn