Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 88 - ThreadStart delegate

Suggested Videos 
Part 85 - Real time example of stack collection class in c#
Part 86 - Multithreading in C#
Part 87 - Advantages and disadvantages of multithreading



In this video we will discuss the purpose of ThreadStart delegate. This is continuation to Part 87. Please watch Part 87 before proceeding.



Let us understand the purpose of ThreadStart delegate with an example.
using System;
using System.Threading;
namespace ThreadStartDelegateExample
{
    class Program
    {
        public static void Main()
        {
            Thread T1 = new Thread(Number.PrintNumbers);
            T1.Start();
        }
    }

    class Number
    {
        public static void PrintNumbers()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}

In the example above to create a THREAD, we created an instance of Thread class and to it's constructor we have passed the name of the function that we want the thread to execute.
Thread T1 = new Thread(Number.PrintNumbers);

We can rewrite the above line using ThreadStart delegate as shown below.
Thread T1 = new Thread(new ThreadStart(Number.PrintNumbers));

Why a delegate need to be passed as a parameter to the Thread class constructor?
The purpose of creating a Thread is to execute a function. A delegate is a type safe function pointer, meaning it points to a function that the thread has to execute. In short, all threads require an entry point to start execution. Any thread you create will need an explicitly defined entry point i.e a pointer to the function where they should begin execution. So threads always require a delegate.

In the code below, we are not explicitly creating the ThreadStart delegate, then how is it working here?
Thread T1 = new Thread(Number.PrintNumbers);

It's working in spite of not creating the ThreadStart delegate explicitly because the framework is doing it automatically for us.

We can also rewrite the same line using delagate() keyword as shown below.
Thread T1 = new Thread(delegate() { Number.PrintNumbers(); });

We can also rewrite the same line using lambda expression as shown below.
Thread T1 = new Thread(() => Number.PrintNumbers());

Thread function need not be a static function always. It can also be a non-static function. In case of non-static function we have to create an instance of the class. An example is shown below.
class Program
{
    public static void Main()
    {
        Number number = new Number();
        Thread T1 = new Thread(number.PrintNumbers);
        T1.Start();
    }
}

class Number
{
    public void PrintNumbers()
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

No comments:

Post a Comment

It would be great if you can help share these free resources