C# Locking Examples & Best Practices
C# lock examples are fundamental in understanding how to control access to shared resources in multi-threaded environments. In this article, we'll delve into the world of locking in C#, exploring the basic lock statement and its variants, along with practical examples.
Locking is a crucial mechanism in C# that ensures exclusive access to shared resources, preventing data inconsistencies and race conditions. It's a way of telling other threads to wait until a specific point in execution has been reached, ensuring your code runs safely and predictably.
Basic Lock Statement
The basic lock statement in C# is used to ensure that only one thread can execute a section of code at a time. It does this by locking an object, which acts as the gateway to the synchronized code block.
Here's a simple example:
lock (lockObject)
{
// Critical section
// Only one thread can be here at a time
}
Lock Object Selection
When choosing an object to lock on, ensure it's immutable and unique across all threads. A common choice is the class or type itself if you're locking on an instance method or property, as shown in this example:
public void SomeMethod()
{
lock (this)
{
// Critical section
}
}
Unlocking and Lock Expressions
In C#, you don't need to explicitly unlock. The lock statement automatically releases the lock when the end of the lock block is reached, so no worries about hanging onto a lock longer than necessary.
Moreover, since C# 5.0, you can use lock expressions, which offer a more concise syntax:
int result = (lock (lockObject) { return criticalSection; });
Monitor Classes
C#'s Monitor class offers lower-level control than the lock statement, providing methods for waiting, pulsing, and signaling threads.
Here's a Wait and Pulse example using Monitor:
private static volatile bool _signal = false;
private static readonly object _locker = new object();
public void SomeMethod()
{
lock (_locker)
{
Monitor.Wait(_locker);
// Some other thread sets _signal to true
}
Monitor.Pulse(_locker);
}
Wait Hand and Wait Any
C# also provides WaitHandle class for waiting on multiple WaitHandles concurrently. It includes methods like WaitAll (all handles must be signaled) and WaitAny (at least one handle must be signaled).
Here's a simple WaitAny example:
var handle1 = new EventWaitHandle(false, EventResetMode.ManualReset);
var handle2 = new EventWaitHandle(false, EventResetMode.ManualReset);
// Some code...
WaitHandle.WaitAny(new[] { handle1, handle2 });
Reader-Writer Locks
When multiple readers and writers need access to a resource, you can use ReaderWriterLockSlim. It offers upgradable read locks, allowing readers to upgrade to a write lock, and also provides controlled access to ensure data integrity.
Here's an example of using ReaderWriterLockSlim:
private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();
public void Read()
{
_locker.EnterReadLock();
// Read critical section
_locker.ExitReadLock();
}
public void Write()
{
_locker.EnterWriteLock();
// Write critical section
_locker.ExitWriteLock();
}
SemaphoreSlim and CountdownEvent
Finally, SemaphoreSlim and CountdownEvent provide additional locking mechanisms for controlling access and signaling threads.
Test these out in your projects, and you'll find them invaluable in orchestrating multithreaded access to shared resources in your C# applications.