The Thread class in C# is part of the System.Threading namespace and provides the fundamental way to create and control threads. A thread represents a path of execution within a process, and using the Thread class you can start, pause, resume, or terminate tasks running concurrently with the main program.
- Defined in System using Threading namespace.
- Represents a single thread of execution.
- Can be created using a delegate (method reference or lambda expression).
- Supports foreground and background modes.
- Provides properties like Name, IsAlive, Priority, and methods like Start(), Sleep(), Abort(), Join().
Creating and Starting a Thread
C# using System; using System.Threading; class Program { static void PrintNumbers() { for (int i = 1; i <= 5; i++) { Console.WriteLine("Worker Thread: " + i); Thread.Sleep(500); } } static void Main() { Thread t1 = new Thread(PrintNumbers); t1.Start(); for (int i = 1; i <= 5; i++) { Console.WriteLine("Main Thread: " + i); Thread.Sleep(500); } } } Output:
Worker Thread: 1
Main Thread: 1
Worker Thread: 2
Main Thread: 2
...
Explanation:
- The main thread and worker thread run concurrently.
- Thread.Sleep(500) pauses execution for half a second, simulating work.
Syntax of C# Thread Class:
Thread t = new Thread(MethodName);
t.Start();
Here:
- Thread is the class.
- MethodName is the method that the thread will execute.
- Start() begins execution of the thread.
Passing Data to a Thread
The Thread class allows passing data through ParameterizedThreadStart or lambda expressions.
1. Using ParameterizedThreadStart
C# class Program { static void PrintMessage(object msg) { Console.WriteLine("Message: " + msg); } static void Main() { Thread t = new Thread(PrintMessage); t.Start("Hello from Thread"); } } Output:
Message: Hello from Thread
2. Using Lambda Expressions
C# Thread t = new Thread(() => { Console.WriteLine("Message from Lambda Thread"); }); t.Start(); Constructor
The Thread class provides multiple constructors to create and initialize threads with or without parameters, and with optional stack size specification.
| Constructor | Description |
|---|
| Thread(ParameterizedThreadStart) | Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when it starts. |
|---|
| Thread(ParameterizedThreadStart, int) | Creates a new Thread instance with a delegate for object passing and sets the maximum stack size. |
|---|
| Thread(ThreadStart) | Initializes a new instance of the Thread class without parameters. |
|---|
| Thread(ThreadStart, int) | Initializes a new instance of the Thread class, specifying the maximum stack size. |
|---|
Example: Using ThreadStart Constructor
C# using System; using System.Threading; public class Geeks { public static void Main() { // Creating and initializing thread using Thread class and ThreadStart constructor Thread t = new Thread(new ThreadStart(Task)); t.Start(); } public static void Task() { for (int j = 0; j < 2; j++) { Console.WriteLine("My Thread is in progress...!!"); } } } OutputMy Thread is in progress...!! My Thread is in progress...!!
Properties
| Property | Description |
|---|
| ApartmentState | Gets or sets the apartment state of this thread. |
|---|
| CurrentContext | Gets the current context in which the thread is executing. |
|---|
| CurrentCulture | Gets or sets the culture for the current thread. |
|---|
| CurrentPrincipal | Gets or sets the thread’s current principal (used for role-based security). |
|---|
| CurrentThread | Gets the currently running thread. |
|---|
| CurrentUICulture | Gets or sets the culture used by the ResourceManager to look up culture-specific resources at runtime. |
|---|
| ExecutionContext | Gets an ExecutionContext object containing information about the various contexts of the current thread. |
|---|
| IsAlive | Gets a value indicating the execution status of the current thread. |
|---|
| IsBackground | Gets or sets a value indicating whether a thread is a background thread. |
|---|
| IsThreadPoolThread | Gets a value indicating whether a thread belongs to the managed thread pool. |
|---|
| ManagedThreadId | Gets a unique identifier for the current managed thread. |
|---|
| Name | Gets or sets the name of the thread. |
|---|
| Priority | Gets or sets the scheduling priority of a thread. |
|---|
| ThreadState | Gets a value containing the states of the current thread. |
|---|
Example: set and get the priority of threads
C# using System; using System.Threading; class Geeks { static public void Main() { // Creating and initializing threads Thread t1 = new Thread(work); Thread t2 = new Thread(work); Thread t3 = new Thread(work); // Set the priority of threads t2.Priority = ThreadPriority.Lowest; t3.Priority = ThreadPriority.AboveNormal; t1.Start(); t2.Start(); t3.Start(); // Display the priority of threads Console.WriteLine("The priority of Thread 1 is: {0}", t1.Priority); Console.WriteLine("The priority of Thread 2 is: {0}", t2.Priority); Console.WriteLine("The priority of Thread 3 is: {0}", t3.Priority); } public static void work() { // Sleep for 100 milliseconds Thread.Sleep(100); } } OutputThe priority of Thread 1 is: Normal The priority of Thread 2 is: Lowest The priority of Thread 3 is: AboveNormal
Commonly Used Methods of the Thread Class in C#
| Method | Description |
|---|
| Start() | Begins execution of the thread. |
|---|
| Sleep(Int32) | Suspends the current thread for a specified time. |
|---|
| Join() | Blocks the calling thread until the target thread finishes. |
|---|
| Abort() | Terminates a thread (obsolete in modern .NET, not recommended). |
|---|
| Interrupt() | Interrupts a thread in Wait, Sleep, or Join state. |
|---|
| Suspend() | Suspends a thread (obsolete, not recommended). |
|---|
| Resume() | Resumes a suspended thread (obsolete, not recommended). |
|---|
| Yield() | Temporarily releases the processor to allow other threads to run. |
|---|
| SpinWait(Int32) | Makes the thread wait actively for a set number of iterations. |
|---|
Less Frequently Used / Advanced Methods
| Method | Description |
|---|
| GetApartmentState() / SetApartmentState(ApartmentState) | Gets or sets the apartment state of a thread. |
|---|
| AllocateDataSlot() / AllocateNamedDataSlot(String) | Creates thread-local data slots. |
|---|
| GetData(LocalDataStoreSlot) / SetData(LocalDataStoreSlot, Object) | Stores or retrieves thread-specific data. |
|---|
| FreeNamedDataSlot(String) | Frees a named data slot. |
|---|
| BeginCriticalRegion() / EndCriticalRegion() | Marks a region where aborts or exceptions affect the application domain. |
|---|
| BeginThreadAffinity() / EndThreadAffinity() | Marks code that depends on the identity of the physical OS thread. |
|---|
| MemoryBarrier() | Ensures correct ordering of memory operations across threads. |
|---|
| VolatileRead() / VolatileWrite() | Provides thread-safe memory read/write operations. |
|---|
Example: Using Start, Sleep, and Join
C# using System; using System.Threading; class Program { static void Task1() { for (int i = 0; i < 3; i++) { Console.WriteLine("Task1 running..."); Thread.Sleep(500); } } static void Main() { Thread t = new Thread(Task1); t.Start(); // Start the thread t.Join(); // Wait until thread finishes Console.WriteLine("Main thread finished"); } } Output:
Task1 running...
Task1 running...
Task1 running...
Main thread finished
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers