Complete C# Tutorial

Multithreading in C# – Run Multiple Tasks Faster

Hey there, coder! πŸ‘‹ Have you ever felt that your program is too slow because it runs tasks one after another? πŸ€”

What if I told you there’s a way to run multiple tasks at the same time and make your application super fast? πŸš€ That’s exactly what Multithreading in C# does!

Let’s dive deep into this exciting topic with real-world examples, complete code, and fun explanations! πŸŽ‰

πŸ”₯ What is Multithreading in C#?

Simply put, Multithreading in C# allows a program to execute multiple tasks at the same time.

Imagine you’re cooking 🍳. Instead of waiting for the rice to cook before frying eggs, you do both at the same time!

That’s exactly how multithreading works in programming. Multiple threads (small units of a process) run in parallel to make your application faster and more efficient.

⚑ Why Use Multithreading in C#?

πŸ”Ή Improves performance by executing tasks simultaneously.
πŸ”Ή Saves time by utilizing CPU power efficiently.
πŸ”Ή Prevents UI freezing in desktop apps.
πŸ”Ή Best for long-running tasks like file processing, downloading, or background computations.

πŸš€ Example 1: Creating a Simple Thread in C#

Β 

βœ… Basic Code Example

				
					using System;
using System.Threading;

class Program
{
    static void PrintMessage()
    {
        Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is running.");
    }

    static void Main()
    {
        Console.WriteLine("Main thread starts.");

        // Creating and starting a new thread
        Thread newThread = new Thread(PrintMessage);
        newThread.Start();

        Console.WriteLine("Main thread ends.");
    }
}
				
			

βœ… Expected Output

				
					Main thread starts.  
Main thread ends.  
Thread 4 is running.  
				
			

πŸ€” What Just Happened?

1️⃣ The main thread started.
2️⃣ A new thread was created to run PrintMessage().
3️⃣ Both threads run in parallel, so order may change.

🎯 Example 2: Running Multiple Threads

Β 

βœ… Code Example

				
					using System;
using System.Threading;

class Program
{
    static void PrintTask(object taskId)
    {
        Console.WriteLine($"Task {taskId} running on Thread {Thread.CurrentThread.ManagedThreadId}");
        Thread.Sleep(1000); // Simulating work
    }

    static void Main()
    {
        Console.WriteLine("Main thread starts.");

        for (int i = 1; i <= 3; i++)
        {
            Thread newThread = new Thread(PrintTask);
            newThread.Start(i);
        }

        Console.WriteLine("Main thread ends.");
    }
}
				
			

βœ… Expected Output

				
					Main thread starts.  
Main thread ends.  
Task 1 running on Thread 4  
Task 2 running on Thread 5  
Task 3 running on Thread 6  
				
			

πŸŽ‰ Here, multiple threads are running in parallel, handling different tasks!

πŸ† Real-World Example: Downloading Multiple Files

Let’s say you’re building a download manager πŸ“₯. Instead of downloading files one by one, multithreading lets you download multiple files at the same time!

πŸ’‘ This is how real-world applications like browsers handle multiple downloads efficiently!

πŸ”„ Thread States in C#

A thread in C# goes through different states:

StateDescription
UnstartedThread is created but not started yet.
RunningThread is currently executing.
WaitingThread is waiting for some operation.
StoppedThread has finished execution.

πŸ’‘ Understanding these states helps in debugging and better thread management!

πŸ”₯ Example 3: Handling Threads with Join()

Sometimes, you want the main thread to wait until another thread finishes. You can use Join() for that!

Β 

βœ… Code Example

				
					using System;
using System.Threading;

class Program
{
    static void PrintNumbers()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}: {i}");
            Thread.Sleep(500);
        }
    }

    static void Main()
    {
        Console.WriteLine("Main thread starts.");

        Thread newThread = new Thread(PrintNumbers);
        newThread.Start();
        newThread.Join(); // Main thread waits until newThread finishes

        Console.WriteLine("Main thread ends.");
    }
}
				
			

βœ… Expected Output

				
					Main thread starts.  
Thread 4: 1  
Thread 4: 2  
Thread 4: 3  
Thread 4: 4  
Thread 4: 5  
Main thread ends.  
				
			

πŸŽ‰ The main thread waits until newThread completes execution!

πŸ”„ Thread Synchronization – Avoiding Race Conditions

  • Sometimes, multiple threads try to access the same resource, causing conflicts.
  • This is called a race condition.
  • You can fix this using locks like lock, Monitor, or Mutex.

Β 

βœ… Example: Using Lock to Prevent Issues

				
					using System;
using System.Threading;

class Program
{
    static object locker = new object();
    static int counter = 0;

    static void IncrementCounter()
    {
        lock (locker)
        {
            counter++;
            Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} incremented counter to {counter}");
        }
    }

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

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

        t1.Join();
        t2.Join();

        Console.WriteLine("Final counter value: " + counter);
    }
}
				
			

βœ… Expected Output

				
					Thread 4 incremented counter to 1  
Thread 5 incremented counter to 2  
Final counter value: 2  
				
			

πŸŽ‰ The lock prevents both threads from modifying counter at the same time!

πŸ“Œ Key Takeaways

➑️ Multithreading in C# allows multiple tasks to run simultaneously.
➑️ Improves performance and responsiveness.
➑️ Use Thread class to create and start threads.
➑️ Use Join() to make a thread wait for another.
➑️ Prevent race conditions using lock.
➑️ Best for CPU-intensive and background tasks.

Β 

πŸš€ Next What?

πŸŽ‰ Great job! Now you know how to use Multithreading in C# effectively!

But wait… πŸ€” Can we make threading even easier?

πŸ”₯ Next up: Task Parallel Library (TPL) in Thread – Making Multithreading Simpler! Stay tuned! πŸš€

Leave a Comment

Share this Doc

Multithreading

Or copy link