Interview Question

What does lock do?

lock serializes access to a critical section using the same gate object.

💡 Concept ✅ Quick Revision 🔷 C#

Answer

The lock statement provides mutually exclusive access to a critical section for a synchronization object. • Only one thread at a time can hold the same lock. • The compiler ensures the lock is released with try-finally semantics. • await cannot be used inside a lock body; use an async-compatible primitive for asynchronous coordination.

💡 C# Example

private readonly object gate = new(); private int count; void Increment() { lock (gate) { count++; } }

⚡ Quick Revision

lock serializes access to a critical section using the same gate object.