Part 90 - Passing data to the Thread function in a type safe manner

Suggested Videos 
Part 87 - Advantages and disadvantages of multithreading
Part 88 - ThreadStart delegate
Part 89 - ParameterizedThreadStart delegate



In this video we will discuss passing data to the Thread function without loosing the type safety feature of C# programming language. This is continuation to Part 89. Please watch Part 89 before proceeding. We will be working with the same example we worked with in Part 89.



To pass data to the Thread function in a type safe manner, encapsulate the thread function and the data it needs in a helper class and use the ThreadStart delegate to execute the thread function. An example is shown below.
using System;
using System.Threading;
namespace ThreadingExample
{
    class Program
    {
        public static void Main()
        {
            // Prompt the user for the target number
            Console.WriteLine("Please enter the target number");
            // Read from the console and store it in target variable
            int target = Convert.ToInt32(Console.ReadLine());

            // Create an instance of the Number class, passing it
            // the target number that was read from the console
            Number number = new Number(target);
            // Specify the Thread function
            Thread T1 = new Thread(new ThreadStart(number.PrintNumbers));
            // Alternatively we can just use Thread class constructor as shown below
            // Thread T1 = new Thread(number.PrintNumbers);
            T1.Start();
        }
    }

    // Number class also contains the data it needs to print the numbers
    class Number
    {
        int _target;
        // When an instance is created, the target number needs to be specified
        public Number(int target)
        {
            // The targer number is then stored in the class private variable _target
            this._target = target;
        }

        // Function prints the numbers from 1 to the traget number that the user provided
        public void PrintNumbers()
        {
            for (int i = 1; i <= _target; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}

Next Video: Retrieving data from Thread function using callback method

Post a Comment

Previous Post Next Post