Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Thread Concept in C#

Thread Concept in C#:-


A thread is the smallest unit of execution within a process. Each thread has its own stack and local variables. In C#, the main thread is the one that executes the Main method. However, you can create additional threads to run tasks in parallel.

Program
  ↓
Process
  ↓
Threads (lightweight subprocesses)

🔹 What is a Thread?

A thread represents a path of execution inside a program.

  • A process can contain multiple threads

  • All threads share the same memory

  • Each thread has its own stack and execution flow

Example:

  • Main thread → handles UI

  • Background thread → downloads data

  • Another thread → processes data

Multithreading Concept in C#:-

Multithreading is a technique in which a single program (process) is divided into multiple threads that execute concurrently while sharing the same resources.

MultithreadingMultiple threads of one program
MultiprocessingMultiple programs/processes
Multitasking (OS)Multiple applications

Single Program
   ↓
Single Process
   ↓
Multiple Threads (Multithreading)

🔍 Real-Time Application Examples

  • Web servers handling multiple requests

  • Banking transaction systems

  • Video streaming apps

  • Chat applications

  • Games (rendering + input + sound)


The thread has four different states:-

1)  Init State:-  When we create Thread Class Object

2)  Runnable State:-  When we start Thread

3) Waiting State:-  When we use sleep() in Thread

4) End State or Destroy State:-  When the process is completed then the end state


Type of Thread:-

1) Single Threading:- 


If we execute only one program at a time then it is called a single thread

 internal class DemoExample
 {
     public void Display()
     {
         for (int i = 1; i <= 5; i++)
         {
             Console.WriteLine("Non-static method running: " + i);
             Thread.Sleep(500);
         }
     }

     static void Main()
     {
         DemoExample obj = new DemoExample();               // object required
         Thread t = new Thread(obj.Display);  // non-static method

         t.Start();
     }
 }

Call using ThreadStart Delegate

class ThreadExample
    {
        static void Display()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Process " + i);
                Thread.Sleep(1000);
            }
        }
        static void Main()
        {
            ThreadStart th = new ThreadStart(ThreadExample.Display);
            Thread t = new Thread(th);
            t.Start();
            Console.ReadKey();
        }
    }

2) Multi-Threading:- 


Multithreading is a concept in which a single program is divided into multiple threads that execute simultaneously.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication2
{
    class ThreadExample
    {
        static void Display()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Process " + i);
                Thread.Sleep(1000);
            }
        }
        static void Main()
        {
            ThreadStart th = new ThreadStart(ThreadExample. Display);
            Thread t = new Thread(th);
            t.Start();
            Thread t1 = new Thread(th);
            t1.Start();
            Console.ReadKey();
        }
    }
}



 What Join() Actually Does

Join() makes the calling thread wait until the specified thread completes its execution.

  • It is used for execution order control

  • It is not a general synchronization mechanism

  • It does not synchronize shared data

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication2
{
    class ThreadExample
    {
        static void Display()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Process " + i);
                Thread.Sleep(1000);
            }
        }
        static void Main()
        {
            ThreadStart th = new ThreadStart(ThreadExample.Display);
            Thread t = new Thread(th);
            t.Start();
            t.Join();
            Thread t1 = new Thread(th);
            t1.Start();
            Console.ReadKey();
        }
    }
}


Thread Synchronization


Thread synchronization is the process of controlling the execution of multiple threads so that shared resources are accessed in a safe and predictable manner.

Thread Synchronization Using lock

🔹 Concept

  • Two threads try to access the same method

  • lock ensures only one thread executes it at a time

What lock Does (Simple Words)

  • Allows only one thread at a time

  • Protects critical section

  • Prevents race condition


using System;
using System.Threading;

class SyncDemo
{
    static object obj = new object(); // lock object

    static void Print()
    {
        lock (obj)   // synchronization
        {
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine(
                    Thread.CurrentThread.Name + " : " + i
                );
                Thread.Sleep(500);
            }
        }
    }

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

        t1.Name = "Thread-1";
        t2.Name = "Thread-2";

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

2. What is Multithreading?

Multithreading means executing multiple threads within a single process concurrently.

For example:

  • Thread 1: Player A plays cricket.

  • Thread 2: Player B plays cricket.

  • Both players play their respective innings concurrently.



3. Two Player One Over Cricket Match Using Multithreading

Match Rules

  • Player A and Player B play 1 over each.

  • Each player gets 6 balls.

  • Runs are randomly generated between 0 and 6.

  • Both players play simultaneously using two threads.

  • After both innings complete, compare scores.

  • Higher score wins.

Complete C# Program


using System;
using System.Threading;

class Program
{
    static int playerARuns = 0;
    static int playerBRuns = 0;

    static object lockObj = new object();

    static void PlayInnings(string player, bool isPlayerA)
    {
        Random random = new Random(
            Guid.NewGuid().GetHashCode());

        int totalRuns = 0;

        for (int ball = 1; ball <= 6; ball++)
        {
            int runs = random.Next(0, 7);

            totalRuns += runs;

            Console.WriteLine(
                $"{player} - Ball {ball}: {runs} Runs");

            Thread.Sleep(500);
        }

        // Thread Synchronization
        lock (lockObj)
        {
            if (isPlayerA)
                playerARuns = totalRuns;
            else
                playerBRuns = totalRuns;

            Console.WriteLine(
                $"{player} Total Score: {totalRuns}");
        }
    }

    static void Main()
    {
        Console.WriteLine("Cricket Match Started!");

        Thread t1 = new Thread(
            () => PlayInnings("Player A", true));

        Thread t2 = new Thread(
            () => PlayInnings("Player B", false));

        // Start both threads
        t1.Start();
        t2.Start();

        // Wait for both innings
        t1.Join();
        t2.Join();

        Console.WriteLine("\nMatch Result:");

        Console.WriteLine($"Player A: {playerARuns}");
        Console.WriteLine($"Player B: {playerBRuns}");

        if (playerARuns > playerBRuns)
            Console.WriteLine("Player A Wins!");
        else if (playerBRuns > playerARuns)
            Console.WriteLine("Player B Wins!");
        else
            Console.WriteLine("Match Draw!");
    }
}

4. Understanding Thread Synchronization

Thread Synchronization means controlling multiple threads when they access shared resources.

Suppose both players update a common variable:

static int totalRuns = 0;

Both threads execute:

totalRuns = totalRuns + runs;

This can create a Race Condition.

For example:

  • Player A reads totalRuns = 10

  • Player B reads totalRuns = 10

  • Player A adds 4 and writes 14

  • Player B adds 6 and writes 16

Expected result = 20, but actual result = 16.

Solution: lock

static object lockObj = new object();

lock (lockObj)
{
    totalRuns += runs;
}


The lock keyword ensures that only one thread at a time enters the protected code block using the same lock object.

In our cricket example: lock protects the shared score variables from concurrent updates. Join() ensures both innings finish before deciding the winner.

Example to differtiate Lock and Join:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp1
{
    internal class JoinBookTickit
    {
        static int tickets = 1;

        static void BookTicket(string name)
        {
            if (tickets > 0)
            {
                Console.WriteLine(name + " checking ticket...");

                Thread.Sleep(1000);

                tickets--;

                Console.WriteLine(name + " booked ticket!");
            }
            else
            {
                Console.WriteLine(name + " ticket not available");
            }
        }

        static void Main()
        {
            Thread t1 = new Thread(() => BookTicket("Rahul"));
            Thread t2 = new Thread(() => BookTicket("Amit"));

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

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

            Console.WriteLine("Remaining Tickets: " + tickets);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp1
{
    internal class LockBookTickit
    {
        static int tickets = 1;
        static object lockObj = new object();

        static void BookTicket(string name)
        {
            lock (lockObj)
            {
                if (tickets > 0)
                {
                    Console.WriteLine(name + " checking ticket...");

                    Thread.Sleep(1000);

                    tickets--;

                    Console.WriteLine(name + " booked ticket!");
                }
                else
                {
                    Console.WriteLine(name + " ticket not available");
                }
            }
        }

        static void Main()
        {
            Thread t1 = new Thread(() => BookTicket("Rahul"));
            Thread t2 = new Thread(() => BookTicket("Amit"));

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

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

            Console.WriteLine("Remaining Tickets: " + tickets);
        }
    }
}


Remember this difference

lock

Prevents Rahul and Amit from booking the same ticket simultaneously.

Join()

Makes Main wait until Rahul and Amit finish booking.

4. Final takeaway

Without lock

With lock

Concurrent access

Yes

Restricted

Race condition

Possible

Prevented for protected operations

Duplicate values

Possible

No

Data consistency

Not guaranteed

Guaranteed for this protected update

5. What is Task in C#?

A Task represents an asynchronous operation that may complete in the future.

Task is available in:

using System.Threading.Tasks;

Think of Task as a modern way to represent work that is running or will run.

Simple Task Example

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Task task = Task.Run(() =>
        {
            Console.WriteLine("Task Started");

            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine(i);
            }
        });

        await task;

        Console.WriteLine("Task Completed");
    }
}

Output:

Task Started
1
2
3
4
5
Task Completed

Task with Return Value

static async Task<int> CalculateRunsAsync()
{
    return await Task.Run(() =>
    {
        int runs = 0;

        for (int i = 1; i <= 6; i++)
        {
            runs += i;
        }

        return runs;
    });
}

Calling this method:

int total = await CalculateRunsAsync();

Console.WriteLine(total); // 21

Important Task types:

Type

Meaning

Task

Operation without return value

Task<T>

Operation returning value of type T

async

Allows asynchronous method implementation

await

Waits asynchronously for Task completion

Task.Run()

Schedules work on ThreadPool          

This is one of the most important concepts in C# multithreading. Many developers confuse Thread, Task, Asynchronous Programming, and Parallel Programming because they are related, but they are not the same.

Let's understand using simple examples.

1. First understand the difference sync vs async

1. Synchronous = One by one (wait for completion)

Example:

Console.WriteLine("Task 1 Started");
Thread.Sleep(3000);
Console.WriteLine("Task 1 Completed");

Console.WriteLine("Task 2 Started");
Console.WriteLine("Task 2 Completed");

Output:

Task 1 Started
Task 1 Completed
Task 2 Started
Task 2 Completed

Task 2 waits until Task 1 completes.

2. Asynchronous = Don't block while waiting

Example:

static async Task Main()
{
    Task task1 = DoWork();

    Console.WriteLine("Task 2 Started");

    await task1;

    Console.WriteLine("Main Completed");
}

static async Task DoWork()
{
    Console.WriteLine("Task 1 Started");

    await Task.Delay(3000);

    Console.WriteLine("Task 1 Completed");
}

Output:

Task 1 Started
Task 2 Started
Task 1 Completed
Main Completed

Task 1 is waiting for 3 seconds, but the Main method can do other work.

3. Remember this difference

Synchronous

Asynchronous

Waits for operation to complete

Can continue other work while waiting

Blocking execution

Non-blocking waiting

One operation completes before the next proceeds

Other operations can make progress during the wait

One important correction to your understanding:

Asynchronous does NOT mean everything executes simultaneously.

For example, an asynchronous API call may be waiting for a server response without occupying a thread.

Remember this simple line:

  • Synchronous = I will wait until you finish.

  • Asynchronous = You continue your work; meanwhile, I will do something else.

And Parallelism = Two workers actually working at the same time.

2. second understand the difference

Imagine you are cooking food.

  • Thread: A worker who performs the work.

  • Task: A unit of work that needs to be completed.

  • Asynchronous: You start a task and don't wait doing nothing. You can do other work while it is in progress.

  • Parallel: Two or more pieces of work actually execute at the same time on different CPU cores.

The most important point:

Asynchronous does not necessarily mean parallel.

2. Thread example

A Thread represents an actual execution thread managed by the operating system.

using System;
using System.Threading;

class Program
{
    static void PrintData()
    {
        Console.WriteLine("Work Started");

        Thread.Sleep(3000);

        Console.WriteLine("Work Completed");
    }

    static void Main()
    {
        Thread t1 = new Thread(PrintData);

        t1.Start();

        Console.WriteLine("Main is working");

        t1.Join();

        Console.WriteLine("Main Completed");
    }
}

Possible output:

Work Started
Main is working
Work Completed
Main Completed

Here:

  • Thread 1 performs the work.

  • Main thread continues doing its work.

  • Join() makes Main wait for Thread 1 to finish.

3. Task example

A Task represents an asynchronous operation or unit of work. It does not necessarily create a new thread.

using System;
using System.Threading.Tasks;

class Program
{
    static async Task PrintData()
    {
        Console.WriteLine("Work Started");

        await Task.Delay(3000);

        Console.WriteLine("Work Completed");
    }

    static async Task Main()
    {
        Task task = PrintData();

        Console.WriteLine("Main is working");

        await task;

        Console.WriteLine("Main Completed");
    }
}

Possible output:

Work Started
Main is working
Work Completed
Main Completed

Notice something interesting: The output looks almost identical to the Thread example!

But the execution is different.

  • Task.Delay(3000) does not block a thread for three seconds.

  • await allows the current method to pause without blocking its thread.

  • Main can continue doing other work.

  • Once the delay completes, execution resumes.

4. The biggest difference: Thread vs Task vs Async

Feature

Thread

Task

Async/Await

Meaning

Execution thread

Unit of work

Non-blocking programming pattern

Creates thread?

Yes, when started

Not necessarily

No, by itself

Can run parallel?

Yes

Yes, depending on execution

Can, but not automatically

Can wait without blocking a thread?

Not directly with Join()

Yes, with await

Yes

Best use

Dedicated thread scenarios

Managing operations

I/O operations

5. Understand asynchronous vs parallel with examples

This is the most important part.

A. Asynchronous programming (not necessarily parallel)

Suppose you download a file from the internet.

static async Task DownloadFile()
{
    Console.WriteLine("Download Started");

    await Task.Delay(3000); // Simulating internet download

    Console.WriteLine("Download Completed");
}

static async Task Main()
{
    Task task = DownloadFile();

    Console.WriteLine("I am doing other work");

    await task;
}

Output:

Download Started
I am doing other work
Download Completed

What happened?

  1. Download started.

  2. Program didn't block a thread waiting for the download.

  3. Main continued doing other work.

  4. After download completed, execution continued.

Asynchronous execution

Illustrative timeline

Download

Waiting for response...

Main

Doing other work

Download waiting does not require a thread to remain blocked.

B. Parallel programming (actual simultaneous execution)

Suppose you want to calculate two large numbers independently.

using System;
using System.Threading.Tasks;

class Program
{
    static void Calculate(string name)
    {
        Console.WriteLine(name + " Started");

        long sum = 0;

        for (int i = 0; i < 100000000; i++)
        {
            sum += i;
        }

        Console.WriteLine(name + " Completed");
    }

    static async Task Main()
    {
        Task t1 = Task.Run(() => Calculate("Task 1"));
        Task t2 = Task.Run(() => Calculate("Task 2"));

        await Task.WhenAll(t1, t2);

        Console.WriteLine("All calculations completed");
    }
}

Here:

  • Task 1 performs calculations.

  • Task 2 performs calculations.

  • Both can execute simultaneously on different CPU cores.

  • Task.WhenAll() waits for both tasks to complete.

Parallel execution

Illustrative timeline

CPU Core 1

Task 1 calculating

CPU Core 2

Task 2 calculating

Two CPU cores can execute the calculations at the same time.

Note: Task.Run() schedules work on the .NET ThreadPool. Parallel execution is possible, but not guaranteed; it depends on available CPU resources and scheduling.

6. One real-world example to remember

Imagine a restaurant:

Concept

Restaurant example

Thread

Waiter

Task

Customer's order

Asynchronous

Waiter places an order in the kitchen and serves another customer while waiting

Parallel

Two cooks prepare different dishes at the same time



6. Two Player Cricket Match Using Task

Now let's implement the same cricket match using Task instead of Thread.


using System;
using System.Threading.Tasks;

class Program
{
    static async Task<int> PlayInnings(string player)
    {
        Random random = new Random(
            Guid.NewGuid().GetHashCode());

        int totalRuns = 0;

        for (int ball = 1; ball <= 6; ball++)
        {
            int runs = random.Next(0, 7);

            totalRuns += runs;

            Console.WriteLine(
                $"{player} - Ball {ball}: {runs} Runs");

            await Task.Delay(500);
        }

        Console.WriteLine(
            $"{player} Total Score: {totalRuns}");

        return totalRuns;
    }

    static async Task Main()
    {
        Console.WriteLine("Match Started!");

        Task<int> playerATask =
            PlayInnings("Player A");

        Task<int> playerBTask =
            PlayInnings("Player B");

        // Wait for both players
        int[] scores = await Task.WhenAll(
            playerATask, playerBTask);

        int playerARuns = scores[0];
        int playerBRuns = scores[1];

        Console.WriteLine("\nMatch Result");

        Console.WriteLine($"Player A: {playerARuns}");
        Console.WriteLine($"Player B: {playerBRuns}");

        if (playerARuns > playerBRuns)
            Console.WriteLine("Player A Wins!");
        else if (playerBRuns > playerARuns)
            Console.WriteLine("Player B Wins!");
        else
            Console.WriteLine("Match Draw!");
    }
}

Important Observation

  • Task.Delay(500) pauses asynchronously without blocking the executing thread.

  • Both player innings begin before Task.WhenAll() waits for their completion.

  • Task.WhenAll() returns both scores after both operations finish.

  • No shared score variable is required because each Task returns its own score.

7. Difference Between Thread and Task

Important Interview Question

Thread

Task

Represents an execution thread

Represents an operation

Low-level programming abstraction

High-level programming abstraction

Created using new Thread()

Created using Task.Run() or async methods

Requires manual thread management

Uses ThreadPool or asynchronous operations

Join() waits synchronously

await waits asynchronously

No built-in result return

Task<T> supports result

No built-in continuation handling

Supports continuations

More control over thread

Easier to manage asynchronous work

Thread vs Task Execution



  • Thread is an actual execution thread managed by the operating system.

  • Task is an abstraction for work or an asynchronous operation.

  • A Task may execute on a ThreadPool thread.

  • A Task using asynchronous I/O may not occupy a thread while waiting.

  • Task does not necessarily mean a new thread.

8. Thread vs Task: Real-Life Cricket Analogy


6

Concept

Cricket Example

Process

Entire cricket match application

Main Thread

Match organizer

Thread

Player playing his innings

Multithreading

Multiple players playing concurrently

Synchronization

Scorekeeper protecting shared scoreboard

Task

An innings represented as an operation

Task.Run

Assign innings work to ThreadPool

async

Organizer can do other work while innings operation is pending

await

Organizer waits for innings result without blocking its thread

Task.WhenAll

Wait for both players' innings



                       

Post a Comment

0 Comments