TrustyCoder
TrustyCoder

Reputation: 4789

aborting timer threads

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.

Upvotes: 1

Views: 2399

Answers (3)

TrustyCoder
TrustyCoder

Reputation: 4789

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.

Upvotes: 0

Oren Mazor
Oren Mazor

Reputation: 4477

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

Upvotes: 4

BlueMonkMN
BlueMonkMN

Reputation: 25601

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.

Upvotes: 1

Related Questions