How do you create thread in C# Multithreading

Answer: To create thread in c# multitheading, we need to use the namespace System.Threading .This name space is used to link the thread assembly file create thread in C# programs.
“using 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 the function is foo ().

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

Program Example – Create thread in C#

using System;

using System.Threading;// use this namespace for threads

namespace threadsample
{
    class Program
    {
        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 t = new Thread(foo); 

		     t.Start();//Start a new thread
            
             
            // Simultaneously, perform some task in main thread also.
             for (int i = 0; i < 5; i++)
             {                
                Console.WriteLine("Main Thread: "+i);
             }
        }

        //function foo(): spawned thread will call this function
        static void foo()  
        {
            for (int i = 0; i < 5; i++) 
             {
                Console.WriteLine("Spawned Thread: " +i);
             }

        }

    }
}

Output:
Spawned Thread: 0
Main Thread: 0
Main Thread: 1
Main Thread: 2
Spawned Thread: 1
Spawned Thread: 2

 

NOTE:  The order of printing output for both main and spawned thread can be random because of parallel execution of threads.For example, at another execution of above program, output can be like below or something else.

Spawned Thread: 0
Spawned Thread: 1
Spawned Thread: 2
Main Thread: 0
Main Thread: 1
Main Thread: 2

Multiple ways to create thread in C# multithreading

1.

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

2.

new Thread (foo).Start();

3.

Thread t = new Thread (new ThreadStart (foo));//using ThreadStart as a delegate
 
t.Start(); 

 

 



Leave a Comment