![]() |
VOOZH | about |
In multithreaded applications, multiple threads often access shared data or resources simultaneously. This can cause race conditions, data inconsistency and unpredictable behavior. Thread synchronization in C# ensures that threads coordinate properly, preventing conflicts and maintaining correctness.
Synchronization ensures thread safety but may reduce performance if overused, as threads spend time waiting for locks to be released.
In C#, synchronized blocks are written using the lock keyword on a specific object. Only one thread can enter the block at a time. Other threads are blocked until the lock is released.
Syntax:
lock(sync_object) {
// Access shared resources
}
Example:
Threads can be synchronized in different ways depending on the requirement. C# provides multiple constructs to handle synchronization:
The lock keyword is the most common way to synchronize threads. It restricts access to a code block so only one thread can execute it at a time.
Thread 3 -> 1 Thread 4 -> 2 Thread 3 -> 3 Thread 4 -> 4 Thread 3 -> 5 Thread 4 -> 6 Thread 3 -> 7 Thread 4 -> 8 Thread 3 -> 9 Thread 4 -> 10
Explanation: Here, both threads attempt to increment counter. Without synchronization, values may overlap or skip. The lock ensures only one thread updates the counter at a time.
The Monitor class provides a more flexible way of synchronizing threads. It works similarly to lock but offers additional control like Wait(), Pulse(), and PulseAll().
Explanation: Monitor.Enter and Monitor.Exit provide explicit control. The try-finally ensures the lock is released even if an exception occurs.
Mutex is used to synchronize threads across multiple processes. Unlike lock, it works not only within a single application but also across different applications.
Explanation: Here, WaitOne() acquires the mutex and ReleaseMutex() releases it. Only one thread across processes can hold the mutex at a time.
A Semaphore controls access to a resource by allowing a specified number of threads to enter at once. This is useful when you want to limit concurrent access.
Explanation: Here, a maximum of 2 threads can work simultaneously. Others wait until a slot is released.
SemaphoreSlim is a lightweight alternative to Semaphore and is recommended for synchronization within a single process.
Explanation: It does not support inter-process synchronization, unlike Semaphore.