Ian Griffiths posted an article on "How To Stop a Thread in .NET", but as Richard Blewett pointed out "...the thread has to be able to check the flag to know it has to bring itself down...".
Richard's solution is better but I prefer another for a number of reasons:
What both articles are talking about is a shutdown event. In which case why not use the timeout for a sleep? So modifying Richard's code we have:
static ManualResetEvent shutdownEvent = new ManualResetEvent(false);static void Main(string[] args){ Thread t = new Thread(new ThreadStart(Func)); t.Start(); Console.ReadLine(); // set the event to get the thread to come down cleanly shutdownEvent.Set(); // wait for it to terminate t.Join();}static void Func(){ // open some resource that requires clean up using(FileStream fs = File.OpenWrite(@"C:\foo.txt")) { // check the event while(!shutdownEvent.WaitOne(10000, true)) { // use the resource fs.WriteByte(0); } }}
Page rendered at Thursday, September 09, 2010 3:49:10 PM (GMT Daylight Time, UTC+01:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.