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 开发者_StackOverflow社区thread? the Thread.CurrentThread points to the calling thread instead of the blocked thread.
Implement your timer as a BackgroundWorker with WorkerSupportsCancellation and check for CancelPending inside your manually written timer?
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.
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.
精彩评论