Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# killing a thread

In my app, I have a thread that runs continuously. By using Thread.Sleep(), the function executes every 10 minutes.

I need to be able to kill this thread when a user clicks a button. I know Thread.Abort() is not reliable. I can use a variable to stop the thread, but since it is sleeping it could be another 10 minutes before the thread kills itself.

Any ideas?

like image 769
Andy Hin Avatar asked Nov 30 '22 05:11

Andy Hin


2 Answers

Why don't you use a timer to schedule the task every ten minutes instead. That will run your code on a thread pool thread and thus you will not have to manage this yourself.

For more details see the System.Threading.Timer class.

like image 62
Brian Rasmussen Avatar answered Dec 15 '22 06:12

Brian Rasmussen


Instead of Thread.Sleep use a System.Threading.ManualResetEvent. The WaitOne method has a timeout just like Thread.Sleep, your thread will sleep for that interval unless the event is triggered first, and the return value tells you whether the interval elapsed or the event was set.

like image 20
Ben Voigt Avatar answered Dec 15 '22 06:12

Ben Voigt