Sobes.tech
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 Mutex or Semaphore for inter-process synchronization.
  • Monitor.Enter and Monitor.Exit for more fine-grained control.
  • ReaderWriterLockSlim for separating read and write locks.

It is important to use a separate private object for locking to avoid deadlocks and ensure safety.