In this example we are going to look at a little bit of a different approach. This will show you how to create a class to handle the background thread. The idea behind this sort of approach is to control the scope of what the different threads can see and operate on. This can help prevent deadlocks and other issues occurring when multiple threads. I am going to be writing multiple posts about this so I will be keeping them very simple to begin with.

The basic idea for this is to create a class which will control the start / stop and running state of the background thread. The reasons for this will become clear in the following posts. For this example I am using the class called ThdExample.

First we will need a few variables to work with.

private Thread Thd = null;
private int Value = 0;

We will have a public start function that can start to execute our thread. You can already see in this function that it will now be impossible for us to accidentally start the same thread twice. This is part of the purpose of wrapping the thread into a single object which is not visible by the rest of the application.

public void Start()
{
        if (Thd != null)
                throw(new Exception("Thread Already Running"));
        Thd = new Thread(new ParameterizedThreadStart(Run));
        Thd.Start();
}

Now we have some code to start a thread we will also need some code to be able to stop the thread from running. Again this code will throw an exception if you attempt to stop a thread that is already stopped.

public void Stop()
{
        if (Thd != null)
        {
                Thd.Abort();
                Thd = null;
        }
        else
        {
                throw (new Exception("Thread Already Stopped"));
        }
}

Since we are running a background thread we do actually want to process something. I did mention I was going to keep this simple. So we are just going to print some increment values to the console. We are also going to wrap an exception handler into the code. So if something does happen we can exit cleanly and also update the state of our object. Since this is the function that the thread was started on if we return from it the thread will cease to exist.

private void Run(object args)
{

        try
        {
                while (true)
                {
                        Value++;

                        Console.WriteLine("Value: {0}", Value);

                        Thread.Sleep(1000);
                }
        }
        catch (Exception ex)
        {

        }
        Thd = null;
}

So you have been following this correctly so far you should have a class where the code looks something like this.

public class ThdExample
{
        private Thread Thd = null;
        private int Value = 0;

        public ThdExample()
        {

        }

        public void Start()
        {
                if (Thd != null)
                        throw(new Exception("Thread Already Running"));
                Thd = new Thread(new ParameterizedThreadStart(Run));
                Thd.Start();
        }

        public void Stop()
        {
                if (Thd != null)
                {
                        Thd.Abort();
                        Thd = null;
                }
                else
                {
                        throw (new Exception("Thread Already Stopped"));
                }
        }

        private void Run(object args)
        {

                try
                {
                        while (true)
                        {
                                Value++;

                                Console.WriteLine("Value: {0}", Value);

                                Thread.Sleep(1000);
                        }
                }
                catch (Exception ex)
                {

                }
                Thd = null;
        }
}

Of course we need a way to test the background task we have written to prove that it is actually working. So lets create a simple program to create two instances of our class and start the background threads, sleep for about ten seconds and then stop the thread and exit the program.

class Program
{
        static void Main(string[] args)
        {
                ThdExample x1 = new ThdExample();
                ThdExample x2 = new ThdExample();

                x1.Start();
                x2.Start();

                Thread.Sleep(10000);

                x1.Stop();
                x2.Stop();

                Console.WriteLine("Done");
                Console.ReadLine();
        }
}

As you can see the code that deals with the threads is now very simple a clean to deal with. Even though our application doesn't really do anything useful here the purpose is to demonstrate a basic structure to build a complex background task on top of. In the next post I will show you how to make this code reusable so that only the run function will need to be written.



Did You find this page useful?

Yes No



Last Modified: 18 February 2017

Releated Posts


2011-10-27 - CSharp - Number Of Cores and Processors
2011-10-04 - CSharp - Thread Queue Example
2011-09-29 - CSharp - Background Thread / Task
2011-09-17 - CSharp - Lookup Hostname
2011-08-29 - C Sharp - StopWatch, The high resolution timer
2011-08-29 - CSharp - IsGuid
2011-08-26 - CSharp - Convert Between Meters and Feet
2011-08-23 - CSharp - ThreadPool and Windows Forms
2011-08-10 - C Sharp - MD5Sum / SHASum
2011-07-22 - CSharp - Fibonacci sum
2011-07-13 - CSharp - Palindrome
2011-07-11 - CSharp - The string Reverse
2011-07-10 - CSharp - Interviews FizzBuzz
2011-06-27 - CSharp - HowTo Parse a URL
2011-06-22 - CSharp - Extending any class
2011-06-13 - ASPNET - Login by username or email
2011-05-12 - CSharp - ASPNET Logoff
2011-03-07 - C Sharp - Windows Logoff
2011-03-02 - ASPNET - Dynamic Controls
2011-03-01 - C Sharp - Resize an image by size of height
2011-02-23 - C Sharp / MSSQL Get inserted value of NEWSEQUENTIALID()
2011-02-10 - CSharp - Shutdown or reboot windows
2011-02-10 - CSharp - Wake on Lan (WOL) Packet
2011-02-06 - C Sharp - Gridview Bound Yes No
2011-02-05 - MSSQL - Levenshtein
2011-01-30 - MSSQL - Adding SHASum support
2011-01-30 - MSSQL - Enabling CLR Functions
2011-01-30 - MSSQL - Adding MD5 checksum support
2011-01-30 - MSSQL - RegEx Support