![]() |
VOOZH | about |
Multithreading in C# is a technique that allows a program to perform multiple operations at the same time by executing different threads concurrently. It is commonly used to improve performance, responsiveness, and efficient resource utilization in applications. C# provides multithreading support through the System. Threading namespace and higher-level abstractions like Task Parallel Library (TPL) and async/await.
A thread is the smallest unit of execution in a program. Every C# program starts with a main thread created automatically by the runtime. You can create additional threads to run tasks in parallel with the main thread.
C# provides multiple ways to create threads:
The Thread class in the System. Threading namespace allows explicit creation and management of threads. This is the most basic way of working with multithreading.
Output:
Worker Thread: 1
Main Thread: 1
Worker Thread: 2
Main Thread: 2
...
Explanation:
Sometimes threads need input data. C# provides the ParameterizedThreadStart delegate to pass parameters to threads.
Output:
Message: Hello from Thread
Instead of separate methods, you can define thread logic inline.
Output:
Lambda Thread: 1
Lambda Thread: 2
Lambda Thread: 3
C# threads can run in two modes:
If the main thread ends before the background thread completes, the background thread is terminated.
When multiple threads access and modify shared data, issues like race conditions can occur. This happens when two or more threads try to update the same variable at the same time, leading to inconsistent results.
To solve this, C# provides synchronization mechanisms. The most common is the lock statement, which ensures that only one thread can access a critical section of code at a time.
Example with Lock:
Creating and destroying threads repeatedly consumes resources. To optimize this, C# provides a Thread Pool, which is a collection of worker threads managed by the runtime. The pool reuses threads for multiple tasks, reducing overhead.
Output (order may vary):
ThreadPool: Task 1
ThreadPool: Task 2
The Task Parallel Library (TPL) provides a modern and easier way to manage multithreading. It abstracts low-level thread management and is highly optimized.
Output (interleaved):
Task 1: 1
Task 2: 1
Task 1: 2
Task 2: 2
...
For I/O-bound operations (like file access, database calls, or API requests), C# provides async and await keywords. These make asynchronous code look like synchronous code, improving readability.
Output:
Fetching...
Data fetched!
Done!