Creating a Thread in C#- Learn what is a thread? and how to create a thread with Explanation and Example programs.

Thread– thread is a light weight process that executes the program independently. Thread able to run the program simultaneously with other threads.


Multi threading – running more than one thread simultaneously to execute the programs. Multi threading supports parallel execution of code.
All threads share the common memory.
Multithreading is similar to multi tasking .

Thread creation in C#

In order to create a thread in c# we need a namespace called System.Threading.
We will be using Thread class to create a thread.First of all, we have to create thread object then pass a user defined function as a parameter to the thread object. Let’s say printNumbers().

For example, Thread t = new Thread (printNumbers); where printNumbers() is a function that a thread will call. Then we need to call t.start() function to start a new thread in c# program.

C# example program to create a thread.

C# Code

using System;
using System.Threading;
class ThreadCreation
    {
        static void Main(string[] args)
        {
            //Create object of a thread class and pass
            //a function as a parameter to it which is called by
            //this thread.

            Thread th = new Thread(printNumbers);

            ////Start a new thread           
            th.Start();

            // Simultaneously, perform some task in main thread also.
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("Main Thread" + i);
            }
        }
        //function printNumbers(): spawned thread will call this function
        static void printNumbers()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("Child Thread" + i);
            }
        }
    }

output-1

Main Thread0
Main Thread1
Main Thread2
Main Thread3
Main Thread4
Child Thread0
Child Thread1

Output-2

Main Thread0
Main Thread1
Main Thread2
Main Thread3
Child Thread0
Child Thread1
Child Thread2
Child Thread3
Child Thread4
Main Thread4

Note:
if we observe the above outputs, we got different results for the same Program.

The order of execution of Main thread and newly created thread can be random because of parallel execution of threads.

Output can’t be same at every time for the above program because of parallel execution.

Thread can be created in multiple ways in C#
1

Thread t = new Thread (printNumbers);
t.Start();

2

new Thread (printNumbers).Start();

3

Thread t = new Thread (new ThreadStart (printNumbers));//using ThreadStart as a delegate

t.Start();

Related Posts