ADVERTISEMENT
ADVERTISEMENT

C# program to create a thread

Here, we are going to learn how to create a thread in C#? Implemental a C# program to create a simple thread.
Submitted by Nidhi, on August 16, 2020

To create a thread in the C# program, here we created a delegate ThreadStart. The ThreadStart delegate is used to point the MyThreadFun() method to execute the thread. Here we passed the ThreadStart delegate as a parameter at the time of the creation of Thread instance. After that, we will call Thread.Start() method to execute the thread.

Program:

The source code to create a thread in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

/*
 * Program to create a thread in C#
 */
using System;
using System.Threading;

class ThreadEx
{
    public void MyThreadFun()
    {
        int i = 0;
        for (i = 1; i<=4; i++)
        {
            Console.WriteLine("Thread Executed");
        }
    }
}
class Program
{
    public static void Main()
    {
        ThreadEx T = new ThreadEx();
        Thread t1 = new Thread(new ThreadStart(T.MyThreadFun));
        t1.Start();
    }
}

Output:

Thread Executed
Thread Executed
Thread Executed
Thread Executed

Explanation:

In the above program, we imported System.Threading namespace to create a thread. Here we created a class ThreadEx that a method MyThreadFun() to implement thread. We also created a Program class that contains the Main() method.

In the Main() method we created object T of class ThreadEx.

Thread t1 = new Thread(new ThreadStart(T.MyThreadFun));

In the above statement we passed the method to delegate ThreadStart and then pass delegate ThreadStart as a parameter in the constructor of Thread class, and then finally called Start() method to execute the thread.

C# Thread Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.