Stopping Thread while it is running in C#

//Stopping Thread while it is running
    public class Worker
    {
        // This method will be called when the thread is started. 
        public void DoWork ( )
        {
            while (!_shouldStop)
            {
                Thread.Sleep ( 1000 );
                Console.WriteLine ( "worker thread: working..." );
            }
            Console.WriteLine ( "worker thread: terminating gracefully." );
        }
        public void RequestStop ( )
        {
            _shouldStop = true;
        }
        // Volatile is used as hint to the compiler that this data 
        // member will be accessed by multiple threads. 
        private volatile bool _shouldStop;
    }

    public class WorkerThreadExample
    {
        static void Main ( )
        {
            // Create the thread object. This does not start the thread.
            Worker workerObject = new Worker ( );
            Thread workerThread = new Thread ( workerObject.DoWork );
           //Following code should be OK as well
           //Thread workerThread = new Thread ( new ThreadStart ( workerObject.DoWork ) );

            // Start the worker thread.
            workerThread.Start ( );
            Console.WriteLine ( "main thread: Starting worker thread..." );

            // Loop until worker thread activates. 
            while (!workerThread.IsAlive) ;

            // Put the main thread to sleep for 1 millisecond to 
            // allow the worker thread to do some work:
            Thread.Sleep ( 1000 );

            while (true)
            {
                char c = Console.ReadKey ( ).KeyChar;
                if (c == 'c' || c == 'C')
                {
                    workerObject.RequestStop ( );
                    break;
                }
            }
            // Use the Join method to block the current thread  
            // until the object's thread terminates.
            workerThread.Join ( );
            Console.WriteLine ( "main thread: Worker thread has terminated." );
        }
    }

This example is same as previous one but it just pass parameter to the thread.

//Passing parameter to worker thread

    public class Worker
    {
        // This method will be called when the thread is started. 
        // If you want to pass own object  then pass it and cast it back the object x
        public void DoWork (object x )
        {
            Console.WriteLine ( "Parameter passed to child thread x = {0}", x.ToString() ); 
            while (!_shouldStop)
            {
                Thread.Sleep ( 1000 );
                Console.WriteLine ( "worker thread: working..." );
            }
            Console.WriteLine ( "worker thread: terminating gracefully." );
        }
        public void RequestStop ( )
        {
            _shouldStop = true;
        }
        // Volatile is used as hint to the compiler that this data 
        // member will be accessed by multiple threads. 
        private volatile bool _shouldStop;
    }

    public class WorkerThreadExample
    {
        static void Main ( )
        {
            // Create the thread object. This does not start the thread.
            Worker workerObject = new Worker ( );
            Thread workerThread = new Thread (   new ParameterizedThreadStart (workerObject.DoWork ));

            // Start the worker thread.
            workerThread.Start ( "Hello my Child thread");
            Console.WriteLine ( "main thread: Starting worker thread..." );

            // Loop until worker thread activates. 
            while (!workerThread.IsAlive) ;

            // Put the main thread to sleep for 1 millisecond to 
            // allow the worker thread to do some work:
            Thread.Sleep ( 1000 );

            while (true)
            {
                char c = Console.ReadKey ( ).KeyChar;
                if (c == 'c' || c == 'C')
                {
                    workerObject.RequestStop ( );
                    break;
                }
            }
            // Use the Join method to block the current thread  
            // until the object's thread terminates.
            workerThread.Join ( );
            Console.WriteLine ( "main thread: Worker thread has terminated." );
        }
    }

We can stop thread also by using Lamda expressions.

//Thread stopping by Lambda expression
        public static void Main ( )
        {
            bool stopped = false;
            Thread t = new Thread ( new ParameterizedThreadStart ( ( x) =>
            {
                while (!stopped)
                {
                    Console.WriteLine ( "Running..." );
                    Thread.Sleep ( 1000 );
                }
            } ) );

            t.Start ( 4);
            Console.WriteLine ( "Press any key to exit" );
            Console.ReadKey ( );
            stopped = true;
            t.Join ( );
        }
    }

Thread synchronization


/// 
/// Thread syncronisation in C#
/// 
namespace Chapter1.Threads
{
    class TaskAsyncExample
    {
        public delegate int HelloMethod(int x);

        public static void Main()
        {
            RunInThreadPoolWithEvents();
            Console.ReadKey();
        }

        static void RunInThreadPoolWithEvents()
        {
            double result = 0d;
            // We use this event to signal when the thread is don executing.
            EventWaitHandle calculationDone = new EventWaitHandle(false, EventResetMode.ManualReset);

            // Save the result of the calculation into another variable
            double result2 = DoIntensiveCalculations();
            Console.WriteLine("Done insentive calculation");

            // Create a work item to read from I/O
            ThreadPool.QueueUserWorkItem((x) => {
                result += ReadDataFromIO();
                Console.WriteLine("Done QueueUserWorkItem calculation");
                calculationDone.Set();
            });

            // Wait for the thread to finish
            calculationDone.WaitOne();
            // Calculate the end result
            result += result2;
            // Print the result
            Console.WriteLine("The result is {0}", result);
        }

        static double ReadDataFromIO()
        {
            // We are simulating an I/O by putting the current thread to sleep.
            Thread.Sleep(10);
            return 10d;
        }

        static double DoIntensiveCalculations()
        {
            // We are simulating intensive calculations
            // by doing nonsens divisions
            double result = 1000d;
            var maxValue = Int32.MaxValue;
            for (int i = 1; i < maxValue; i++)
            {
                result /= i;
            }
            return result + 10d;
        }
    }
}