Sobes.tech
Junior — Middle

What tools do you use to prevent conflicts when working with threads simultaneously?

sobes.tech AI

Answer from AI

To prevent conflicts when multiple threads operate simultaneously in C#, various synchronization mechanisms are used:

  • lock — a simple way to lock a critical section of code.
  • Mutex — an inter-process mutex for synchronization between processes.
  • Semaphore / SemaphoreSlim — limits the number of threads executing code simultaneously.
  • Monitor — a more flexible locking mechanism on which lock is based.
  • Concurrent collections (e.g., ConcurrentDictionary) — collections safe for multi-threaded access.
  • Interlocked — atomic operations on variables.

Example of using lock:

private readonly object _lockObj = new object();

void IncrementCounter() {
    lock(_lockObj) {
        counter++;
    }
}

This approach prevents simultaneous access to the variable counter and avoids race conditions.