Curriculum
Multithreading in C# is a powerful programming technique that allows multiple parts of an application to execute simultaneously. Multithreading in C# helps developers improve application performance, responsiveness, scalability, and resource utilization. Modern ASP.NET Core Applications, Enterprise Software Systems, Banking Applications, E-Commerce Platforms, Cloud Applications, Game Development Projects, and Desktop Applications heavily rely on Multithreading in C# to process multiple tasks efficiently.
Understanding Multithreading in C# is essential because modern processors contain multiple CPU cores, and software applications must utilize these resources effectively to achieve high performance.
Multithreading in C# is the process of executing multiple threads within a single application simultaneously.
A thread represents the smallest unit of execution inside a process.
Example:
Application
|
|---- Thread 1
|---- Thread 2
|---- Thread 3
Each thread performs its own task independently.
A Process is a running instance of an application.
Examples:
Google Chrome
Visual Studio
Microsoft Word
Spotify
Every process contains one or more threads.
Example:
Process
|
|---- Main Thread
Additional threads can be created when needed.
Multithreading in C# helps:
Large-scale applications depend heavily on multithreading.
Task 1
↓
Task 2
↓
Task 3
Tasks execute one after another.
Task 1 → Thread 1
Task 2 → Thread 2
Task 3 → Thread 3
Tasks execute simultaneously.
This significantly improves efficiency.
Imagine a banking application.
Without Multithreading:
Process Transaction
Generate Receipt
Send SMS
Each task waits for the previous task.
With Multithreading:
Transaction Thread
Receipt Thread
SMS Thread
All tasks can execute concurrently.
Namespace:
using System.Threading;
Basic Example:
public static void Display()
{
Console.WriteLine(
"Thread Started");
}
Create Thread:
Thread thread =
new Thread(Display);
thread.Start();
Output:
Thread Started
A new thread is created and executed.
Example:
Thread thread =
new Thread(() =>
{
Console.WriteLine(
"Thread Running");
});
Start:
thread.Start();
Output:
Thread Running
This is a cleaner approach.
Every C# application starts with:
Main Thread
Example:
static void Main()
{
}
The Main Method executes on the primary thread.
Additional threads can be created as needed.
A thread passes through several states.
Thread created but not started.
Thread actively executing.
Thread temporarily paused.
Thread execution completed.
Lifecycle:
Unstarted
↓
Running
↓
Wait
↓
Stopped
Understanding lifecycle states is important for debugging.
Thread.Sleep pauses execution.
Example:
Console.WriteLine(
"Start");
Thread.Sleep(3000);
Console.WriteLine(
"End");
Output:
Start
(3 Seconds Delay)
End
Useful for simulations and timing operations.
Join waits for a thread to complete.
Example:
Thread thread =
new Thread(Display);
thread.Start();
thread.Join();
The main thread waits until the child thread finishes.
Two types of threads exist.
Keeps the application alive.
Stops automatically when the application exits.
Example:
thread.IsBackground =
true;
Background threads are commonly used for monitoring tasks.
Priority determines execution preference.
Example:
thread.Priority =
ThreadPriority.Highest;
Available priorities:
Lowest
BelowNormal
Normal
AboveNormal
Highest
Priority influences thread scheduling.
Multiple threads may access the same resource simultaneously.
Example:
Bank Account
Database Record
Shared File
Without synchronization:
Data Corruption
may occur.
A Race Condition occurs when multiple threads modify shared data simultaneously.
Example:
balance = balance - 100;
If multiple threads execute this statement together:
Incorrect Results
may occur.
Race conditions are serious issues in concurrent systems.
The lock keyword prevents simultaneous access.
Example:
private static object
locker =
new object();
Usage:
lock(locker)
{
balance =
balance - 100;
}
Only one thread can enter the block at a time.
Benefits:
Locking is widely used in enterprise applications.
Class:
public class BankAccount
{
private int balance =
10000;
private object locker =
new object();
public void Withdraw(
int amount)
{
lock(locker)
{
balance -= amount;
Console.WriteLine(
balance);
}
}
}
This ensures thread-safe transactions.
Monitor provides advanced synchronization.
Example:
Monitor.Enter(locker);
try
{
// Critical Section
}
finally
{
Monitor.Exit(locker);
}
Lock internally uses Monitor.
Monitor offers greater flexibility.
Mutex synchronizes threads across processes.
Example:
Mutex mutex =
new Mutex();
Used for:
Single Application Instance
Cross Process Synchronization
Mutex is common in desktop applications.
Semaphore allows limited concurrent access.
Example:
Semaphore semaphore =
new Semaphore(
2,
2);
Meaning:
Maximum 2 Threads Allowed
Useful for resource pools.
Deadlock occurs when two or more threads wait indefinitely.
Example:
Thread A Waiting for B
Thread B Waiting for A
Result:
Application Freeze
Deadlocks must be avoided.
Best practices:
Deadlock prevention is a critical skill.
Examples:
Request Processing
Background Services
Email Sending
Report Generation
ASP.NET Core internally uses multiple threads.
Transactions
Notifications
Report Processing
Order Processing
Inventory Updates
Payment Verification
Patient Management
Appointment Scheduling
Medical Reports
Attendance Processing
Exam Evaluation
Notification Systems
Multithreading improves scalability and performance.
Multiple tasks execute simultaneously.
User interfaces remain responsive.
Multiple cores can be used effectively.
Supports large applications.
Background operations execute concurrently.
These benefits are essential for enterprise systems.
Can cause race conditions.
Consumes system resources.
Reduces performance.
Can freeze applications.
Creates inconsistent results.
Multithreading is the execution of multiple threads simultaneously within an application.
A Thread is the smallest unit of execution within a process.
A Race Condition occurs when multiple threads modify shared data simultaneously.
Lock prevents multiple threads from accessing a critical section at the same time.
A Deadlock occurs when threads wait indefinitely for each other.
Multithreading improves performance, responsiveness, and scalability.
Multithreading allows multiple threads to execute concurrently within an application.
It improves performance, scalability, and responsiveness.
A Race Condition occurs when multiple threads access shared data simultaneously.
The lock keyword ensures only one thread accesses a critical section at a time.
A Deadlock occurs when threads block each other indefinitely.
It enables high-performance, scalable, and responsive enterprise applications.
WhatsApp us