Junior — Middle
What methods can be used to implement safe resource locking inside a class?
sobes.tech AI
Answer from AI
In C#, the lock keyword is commonly used for safe resource locking within a class. It allows synchronization of access to shared resources, preventing race conditions.
Example:
private readonly object _lockObject = new object();
public void SafeMethod()
{
lock (_lockObject)
{
// Code that should execute atomically
}
}
Other methods:
- Using
MutexorSemaphorefor inter-process synchronization. Monitor.EnterandMonitor.Exitfor more fine-grained control.ReaderWriterLockSlimfor separating read and write locks.
It is important to use a separate private object for locking to avoid deadlocks and ensure safety.