C# More on threading, killing a thread, waiting for, or how to do a Thread.Join

In my last post I used a ThreadPool to do some work. ThreadPools are great and I use them a lot. However many times I find myself really only needing 1 thread and I need to have some control over it. I may need to wait for it to finish, or more importantly I need to be able to control when it dies or completes its task. For this case I always use Thread.Join

As usual please peruse the MSDN documentation.

Thread.Join waits for the thread to complete before proceeding with any other operations. So simply creating a thread then calling Thread.Join can be useful in some UI operations I tend to not call Join until I'm ready to kill the thread entirely. The MSDN link above goes over the great details.

Now let's go over some quick code. This example creates a thread then waits for the user to press a key and terminates the thread.

Let's look at the main console code

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ThreadExample
{
    class Program
    {
        static void Main( string[] args )
        {
            // create a class for use in threading
            ThreadWorker worker = new ThreadWorker();
            worker.IsAlive = true;

            // let's create a thread to do some work
            // pass the worker classes DoWork method as the method to do the work in
            Thread t = new Thread( new ThreadStart( worker.DoWork ) );

            // start the thread
            t.Start();

            // let the thread run while we wait for a key press
            Console.ReadKey();

            // send the kill signal
            // and do the join to wait for processing to end
            worker.IsAlive = false;
            t.Join();

            Console.WriteLine( "Press any key to terminate..." );
            Console.ReadKey();

        }
    }
}

It starts a thread, sets it to be alive and then waits for a key press. Once they key is pressed it sets IsAlive to false and waits for the thread to terminate. Now let's look at the thread code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ThreadExample
{
    public class ThreadWorker
    {
        private volatile bool _isAlive = false;

        public bool IsAlive
        {
            get { return _isAlive; }
            set { _isAlive = value; }
        }

        public ThreadWorker()
        {
        }

        public void DoWork()
        {
            int i = 0;

            while( _isAlive )
            {
                Console.WriteLine( "Current iteration is {0}", i++ );
                Thread.Sleep( 100 );
            }
        }
    }
}

This thread takes a volatile bool (used for thread safety, not the best method, but it works for this example) and simply writes to the console while it's in the alive state.

Here is the output from the program


As you can see the thread runs until a key press is made and it terminates. This is a very basic example on how to create a thread and send it a kill signal. I used to be a big background worker user, but I find this method much quicker and easier to setup and use.

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC