Sobes.tech
Middle

What are locks in C#?

sobes.tech AI

Answer from AI

lock in C# is used to ensure exclusive access to a block of code. It guarantees that only one thread can execute that block at a time, preventing race conditions when working with shared resources.

private static readonly object _lockObject = new object(); // Synchronization object

public void AccessSharedResource()
{
    lock (_lockObject) // Locking the object
    {
        // Critical section: code that requires exclusive access
        // Working with shared resource (e.g., modifying a variable)
    } // Lock is automatically released when exiting the block
}

Alternatives and related concepts:

  • Monitor: Provides more granular control over synchronization, including methods Wait, Pulse, PulseAll.
  • Mutex: Used for synchronization between processes, as well as threads within a single process.
  • Semaphore/SemaphoreSlim: Limits the number of threads that can access a resource simultaneously.
  • ReaderWriterLockSlim: Allows multiple threads to read simultaneously, but only one to write.

The choice of locking mechanism depends on the specific synchronization task. lock is a shorthand for using Monitor.Enter and Monitor.Exit and is suitable for most simple synchronization cases within a single process.

What are locks in C#? — C# - sobes.tech