Sobes.tech
Junior — Middle

How did you ensure synchronization when sharing resources?

sobes.tech AI

Answer from AI

For synchronization when sharing resources in C#, various locking mechanisms are typically used to avoid race conditions and ensure correct data access.

Main methods:

  • lock — the most common method, using a dummy object to lock a critical section.
private readonly object _lockObj = new object();

void UpdateResource()
{
    lock(_lockObj)
    {
        // code working with the shared resource
    }
}
  • Mutex — used for inter-process synchronization.

  • Monitor — a more flexible mechanism based on lock.

  • Semaphore/SemaphoreSlim — to limit the number of threads working with the resource simultaneously.

  • Concurrent collections (e.g., ConcurrentDictionary) — for thread-safe access without explicit locks.

The choice depends on the specific task and requirements for performance and security.

How did you ensure synchronization when sharing… - sobes.tech