How to Use Thread Class in C#: Simple Guide with Examples
In C#, use the
Thread class to run code on a separate thread by creating a Thread object with a method to execute, then start it with Start(). This allows your program to perform tasks concurrently, improving responsiveness or performance.Syntax
The Thread class is used to create and control a thread. You create a new thread by passing a ThreadStart delegate or a lambda expression to the Thread constructor. Then, call Start() to begin execution.
- Thread thread = new Thread(MethodName); - creates a new thread that will run
MethodName. - thread.Start(); - starts the thread.
csharp
Thread thread = new Thread(MethodName);
thread.Start();Example
This example shows how to create a thread that runs a method printing numbers from 1 to 5 while the main thread prints letters. Both run at the same time.
csharp
using System; using System.Threading; class Program { static void PrintNumbers() { for (int i = 1; i <= 5; i++) { Console.WriteLine($"Number: {i}"); Thread.Sleep(500); // Pause for half a second } } static void Main() { Thread thread = new Thread(PrintNumbers); thread.Start(); for (char c = 'A'; c <= 'E'; c++) { Console.WriteLine($"Letter: {c}"); Thread.Sleep(700); // Pause for 0.7 seconds } thread.Join(); // Wait for the thread to finish Console.WriteLine("Main thread finished."); } }
Output
Number: 1
Letter: A
Number: 2
Letter: B
Number: 3
Letter: C
Number: 4
Letter: D
Number: 5
Letter: E
Main thread finished.
Common Pitfalls
Some common mistakes when using Thread include:
- Not calling
Start()on the thread, so it never runs. - Accessing shared data without synchronization, causing data corruption.
- Not using
Join()if you need to wait for the thread to finish before continuing. - Creating threads for very short tasks, which can be inefficient.
Always ensure thread safety and proper thread lifecycle management.
csharp
/* Wrong: Thread created but not started */ Thread thread = new Thread(() => Console.WriteLine("Hello")); // thread.Start(); // Missing start call /* Right: Start the thread */ Thread thread2 = new Thread(() => Console.WriteLine("Hello")); thread2.Start();
Output
Hello
Quick Reference
| Action | Code Example | Description |
|---|---|---|
| Create Thread | Thread t = new Thread(Method); | Creates a new thread to run Method. |
| Start Thread | t.Start(); | Begins execution of the thread. |
| Wait for Thread | t.Join(); | Blocks current thread until t finishes. |
| Sleep Thread | Thread.Sleep(1000); | Pauses current thread for 1 second. |
Key Takeaways
Create a Thread object with a method to run and call Start() to run it.
Use Join() to wait for a thread to finish if needed.
Avoid accessing shared data without synchronization to prevent errors.
Do not forget to call Start(), or the thread will not run.
Use Thread.Sleep() to pause a thread safely.