How to Create Threads in C#?
Last Updated :
11 Jul, 2025
Multithreading enables concurrent task execution in C#. It improves performance and responsiveness. We can create threads using the System.Threading namespace. With the help of Threads, we can achieve multitasking and can define their behavior using different methods provided by the Thread Class.
Example: This example shows how to create and start a thread using Thread Class in C#.
C#
// C# Program to create and start a thread
// using Thread Class
using System;
using System.Threading;
class Geeks
{
static void Main()
{
// Create a new thread and start it
Thread thread = new Thread(new ThreadStart(Worker));
thread.Start();
// Do some work in the main thread
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Main thread: {0}", i);
Thread.Sleep(100);
}
// Wait for the worker thread to finish
thread.Join();
}
static void Worker()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Worker thread: {0}", i);
Thread.Sleep(100);
}
}
}
OutputMain thread: 0
Worker thread: 0
Main thread: 1
Worker thread: 1
Main thread: 2
Worker thread: 2
Explanation: In this example, we create a new thread using the Thread class and pass in a delegate to the Worker method. We then start the thread using the Start method. Then we have used the join method to wait until the other thread completes it works.
Note: While creating thread make sure to properly synchronize access to shared data between threads to avoid race conditions and other synchronization issues.
Steps to Create a Thread
Step 1: importing System.Threading namespace
First, import the System.Threading namespace. It plays an important role in creating a thread in our program, as it allows us to use thread-related classes without specifying their fully qualified names every time.
using System;
using System.Threading;
Step 2: Creation and Initialization
Now, create and initialize the thread object in main method.
public static void main()
{
Thread thr = new Thread(job1);
}
Step 3: Starting the Thread
Start the thread using the Start method.
public static void main()
{
Thread thr = new Thread(job1);
thr.Start();
}
Example:
C#
// C# program to illustrate the
// creation of thread using
// non-static method
using System;
using System.Threading;
public class ExThread
{
// Non-static method
public void mythread1()
{
for (int z = 0; z < 3; z++)
{
Console.WriteLine("First Thread");
}
}
}
class Geeks
{
public static void Main()
{
// Creating object of ExThread class
ExThread obj = new ExThread();
// Creating thread
// Using thread class
Thread thr = new Thread(new ThreadStart(obj.mythread1));
thr.Start();
}
}
OutputFirst Thread
First Thread
First Thread
Explanation: In the above example, we create an instance (obj) of the ExThread class and pass its method (mythread1) to the ThreadStart delegate. Then, we create a thread (thr) and start it using thr.Start()
to execute the method in a separate thread.
Example:
C#
// C# program to illustrate the creation
// of thread using static method
using System;
using System.Threading;
public class ExThread
{
// Static method for thread a
public static void thread1()
{
for (int i = 0; i < 3; i++)
Console.WriteLine(i);
}
// static method for thread b
public static void thread2()
{
for (int i = 0; i < 3; i++)
Console.WriteLine(i);
}
}
class Geeks
{
public static void Main()
{
// Creating and initializing threads
Thread a = new Thread(ExThread.thread1);
Thread b = new Thread(ExThread.thread2);
a.Start();
b.Start();
}
}
Explanation: In the above example, The ExThread contains two static methods thread1() and thread2(). So we do not need to create an instance of ExThread class. Here, we call these methods using a class name, we create and initialize the work of thread a, similarly for thread b. By using a.Start(); and b.Start(); statements, a and b threads scheduled for execution.
Note: The output of these programs may vary due to context switching.
Different Ways to Create Threads
- Using Thread Class
- Using Task Class
- Using ThreadStart Delegate
1. Using Thread Class
In C# Thread Class is used to create and manage threads, providing greater control over multithreading. It allows operations such as setting thread priorities, managing thread states, and handling synchronization. We can perform multiple operations on threads, set thread priorities, manage thread states, and handle synchronization mechanisms to prevent race conditions.
Example:
C#
// Create thread using Thread class
using System;
using System.Threading;
class Geeks
{
static void Main()
{
// Creating a thread using Thread Class
Thread thread = new Thread(() => {
Console.WriteLine("Thread is running....");
});
thread.Start();
thread.Join();
}
}
OutputThread is running....
2. Using Task Class
In C# Task class is part of the Task Parallel Library (TPL) and is used for managing and running asynchronous operations or parallel tasks. It simplifies multithreading by abstracting the complexity of thread management and provides a more scalable and efficient way to handle concurrent operations.
Example:
C#
// Create thread using Task Class
using System;
using System.Threading.Tasks;
class Geeks
{
static void Main()
{
// Creating a Task
Task task = Task.Run(() => {
Console.WriteLine("Task is running......");
});
task.Wait();
}
}
OutputTask is running......
3. ThreadStart Delegate
The ThreadStart delegate in C# specifies the method to execute when a thread starts. It represents a method that takes no parameters and returns void. The delegate allows a method to be passed directly to the Thread constructor for execution in a separate thread. It simplifies creating and starting threads by allowing us to pass a method directly to the Thread constructor for execution on a separate thread.
Example:
C#
// Create thread using ThreadStart Delegate
using System;
using System.Threading;
class Geeks
{
public static void Main(string[] args)
{
Console.WriteLine("Program start");
// Create and start a new thread
// using ThreadStart delegate
Thread newThread = new Thread(new ThreadStart(() =>
{
Console.WriteLine("Thread started..");
// sleep for 100 milliseconds
Thread.Sleep(100);
Console.WriteLine("Thread finished..");
}));
newThread.Start();
}
}
OutputProgram start
Thread started..
Thread finished..
Classes Used in Thread
In C#, a multi-threading system is built upon the Thread class, which encapsulates the execution of threads. This class contains several methods and properties which help in managing and creating threads and this class is defined under System.Threading namespace. The System.Threading namespace provides classes and interfaces that are used in multi-thread programming. Some commonly used classes in this namespace are:
Class | Description |
---|
Thread | This is used to create and control a thread, set its priority, and get its status. |
---|
Mutex | It is a synchronization primitive that can also be used for IPS (interprocess synchronization). |
---|
Monitor | This class provides a mechanism that accesses objects in a synchronized manner. |
---|
Semaphore | Used to limit the number of threads that can access a resource or pool of resources concurrently. |
---|
ThreadPool | Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers. |
---|
ThreadLocal | Provides thread-local storage of data. |
---|
Timer | Provides a mechanism for executing a method on a thread pool thread at specified intervals. We are not allowed to inherit this class. |
---|
Volatile | Contains methods for performing volatile memory operations |
---|
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers