Complete C# Tutorial

Mastering Threads in C# – Easy Guide with Examples

Hey there, coder! πŸ˜ƒ Ever noticed how some applications freeze up while doing heavy tasks, but others stay smooth no matter what? The secret is Threads in C#!

Multithreading lets you run multiple tasks at the same time, making your app faster and more efficient. In this friendly guide, we’ll break it all down with simple Threads Examples in C# so you can master multithreading like a pro! πŸ’ͺ

🎯 What are Threads in C#?

A thread is like a tiny worker inside your app. It can run tasks independently without waiting for others to finish.

Imagine a restaurant 🍽️. Without threads, the chef cooks one dish at a time while customers wait. But with threads, multiple chefs cook different dishes at the same timeβ€”way faster!

πŸ’‘ In C#, threads help apps:

  1. Perform multiple tasks at once
  2. Prevent UI from freezing
  3. Utilize CPU power efficiently

Now, let’s see Threads Examples in C# in action!

πŸ›  Understanding the System.Threading Namespace

In C#, threads belong to the System.Threading namespace. This contains everything you need to create, manage, and control threads.

Before using threads, always import this namespace:

				
					using System.Threading;
				
			

Without this, you can’t use the Thread class in C#.

πŸš€ Creating and Starting a Thread (Thread Class)

Let’s start with a basic example of creating and starting a thread.

Β 

βœ… Example: Creating and Running a Thread

				
					using System;
using System.Threading;

class Program
{
    static void PrintMessage()
    {
        Console.WriteLine("Hello from the new thread!");
    }

    static void Main()
    {
        Thread newThread = new Thread(PrintMessage);
        newThread.Start();

        Console.WriteLine("Main thread is running...");
    }
}
				
			

πŸ–₯️ Output:

				
					Main thread is running...
Hello from the new thread!
				
			

πŸŽ‰ What happens here?


1️⃣ The Main thread starts as usual.
2️⃣ A new separate thread (newThread) is created.
3️⃣ newThread.Start(); runs PrintMessage() in parallel to the Main thread.

Boom! You just created your first thread in C#! πŸš€

πŸ”„ Running Multiple Threads in Parallel

What if we run multiple threads at once?

Β 

βœ… Example: Running Multiple Threads

				
					using System;
using System.Threading;

class Program
{
    static void PrintNumbers()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} prints {i}");
            Thread.Sleep(1000); // Simulate work
        }
    }

    static void Main()
    {
        Thread t1 = new Thread(PrintNumbers);
        Thread t2 = new Thread(PrintNumbers);

        t1.Start();
        t2.Start();

        Console.WriteLine("Main thread continues running...");
    }
}
				
			

πŸ–₯️ Output (Varies each time):

				
					Main thread continues running...
Thread 4 prints 1
Thread 5 prints 1
Thread 4 prints 2
Thread 5 prints 2
...
				
			

πŸ”₯ Threads t1 and t2 run in parallel! You don’t know which will finish first because they run independently. That’s the beauty of multithreading!

🚦 Setting Thread Priorities (ThreadPriority)

Sometimes, you want one thread to run faster than others. You can set priorities like this:

Β 

βœ… Example: Using Thread Priorities

				
					Thread t1 = new Thread(PrintNumbers);
t1.Priority = ThreadPriority.Highest; // Runs faster!

Thread t2 = new Thread(PrintNumbers);
t2.Priority = ThreadPriority.Lowest; // Runs slower!
				
			

Priorities: Lowest, BelowNormal, Normal, AboveNormal, Highest

πŸ“Œ Note: The OS still decides execution order, so don’t fully rely on priorities!

⚠️ Handling Exceptions in Threads

Threads may fail due to errors. Let’s handle them!

Β 

βœ… Example: Exception Handling in Threads

				
					static void RiskyTask()
{
    try
    {
        throw new Exception("Something went wrong!");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Caught Exception: {ex.Message}");
    }
}

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

πŸ–₯️ Output:

				
					Caught Exception: Something went wrong!
				
			

🎯 Always wrap risky code in try-catch to prevent crashes!

🎯 Passing Parameters to a Thread

Sometimes, you need to send data to a thread.

Β 

βœ… Example: Passing Parameters to a Thread

				
					using System;
using System.Threading;

class Program
{
    static void PrintMessage(object name)
    {
        Console.WriteLine($"Hello, {name}!");
    }

    static void Main()
    {
        Thread t = new Thread(PrintMessage);
        t.Start("Alice"); // Passing "Alice" as parameter
    }
}
				
			

πŸ–₯️ Output:

				
					Hello, Alice!
				
			

πŸŽ‰ The PrintMessage method receives “Alice” as input!

🌍 Real-World Example – Downloading Files

Think of a file downloader. You want to download multiple files at once instead of waiting for each one.

Β 

βœ… Example: File Download Simulation

				
					using System;
using System.Threading;

class Program
{
    static void DownloadFile(object file)
    {
        Console.WriteLine($"Downloading {file}...");
        Thread.Sleep(3000); // Simulating 3 sec download
        Console.WriteLine($"{file} Downloaded!");
    }

    static void Main()
    {
        Thread t1 = new Thread(DownloadFile);
        Thread t2 = new Thread(DownloadFile);

        t1.Start("File1.pdf");
        t2.Start("File2.mp3");

        Console.WriteLine("Main thread keeps running...");
    }
}
				
			

πŸ–₯️ Output:

				
					Main thread keeps running...
Downloading File1.pdf...
Downloading File2.mp3...
File1.pdf Downloaded!
File2.mp3 Downloaded!
				
			

πŸ”₯ Now, downloads happen in parallel instead of one-by-one!

🎯 Conclusion

Congrats, you did it! πŸŽ‰ You now have a solid understanding of Threads in C# and how they help make applications faster, more efficient, and responsive.

We explored:


βœ… What Threads in C# are and why they are important
βœ… How to create and start threads
βœ… Running multiple threads in parallel
βœ… Setting thread priorities
βœ… Handling exceptions in threads
βœ… Passing parameters to a thread
βœ… A real-world example of using threads

Threads are powerful, but they also need careful management to avoid issues like deadlocks and race conditions. Don’t worryβ€”we’ll tackle those in the next lesson! πŸš€

Β 

⏭️ Next What?

Now that you know how to create and manage threads, the next step is understanding the Thread Lifecycle and Management in C#. We’ll learn how to pause, stop, and properly handle threads for smooth execution. Stay tuned! 😊

Leave a Comment

Share this Doc

Working with Threads

Or copy link