# Saturday, November 13, 2004
« Halo 2 | Main | Referral Spam 2 »

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:

  • The code could be waiting for 2 seconds before the Sleep gets interrupted
  • We can get rid a a few lines of code
  • I think this solution is clearer

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);
        }
    }
}

This posting is provided "AS IS" with no warranties, and confers no rights.
posted on Saturday, November 13, 2004 2:03:02 PM (GMT Standard Time, UTC+00:00)  #    Comments [2] Trackback
Related posts:
Testing Windows Forms Applications
Messing around with the Insert Code plug-in
Link Dump
Debugging FullTrust VSTO InfoPath Forms
Which version of the .NET Framework does Excel load?
Missing content from XmlSerializer output
Thursday, November 18, 2004 5:56:40 PM (GMT Standard Time, UTC+00:00)
A couple of comments:

The sleep was simply to emulate stuff happening that cannot check the boolean flag - waiting on an event for example - in a way that puts the thread in a WaitSleepJoin state and so can be alerted by thread.Interrupt.

The two second timeout in my Main is obviously something that is configurable.

The solution you have stops any work taking place on a regular basis while checking whether the event for a period of time. You could reduce the timout to 0, but in that case you might as well use a boolean flag.
Thursday, November 18, 2004 6:36:13 PM (GMT Standard Time, UTC+00:00)
I guess I was confused about the reasons for sleeping - we often have a situation where you have a thread doing work, waiting and then starting again. I mistook your pattern for that.

However, for a thread to be in WaitSleepJoin it has to be doing one of those three things. For sleep see my previous example, if you are waiting on another object then why not WaitAny() on both the object and the shutdown event; finally, if you are joining then the pattern repeats (even using the same event if that is possible).
Comments are closed.