Tutorial by Examples

Common usage of lock is a critical section. In the following example ReserveRoom is supposed to be called from different threads. Synchronization with lock is the simplest way to prevent race condition here. Method body is surrounded with lock which ensures that two or more threads cannot execute i...
Following code will release the lock. There will be no problem. Behind the scenes lock statement works as try finally lock(locker) { throw new Exception(); } More can be seen in the C# 5.0 Specification: A lock statement of the form lock (x) ... where x is an expression of a referenc...
Following code will release lock. lock(locker) { return 5; } For a detailed explanation, this SO answer is recommended.
When using C#'s inbuilt lock statement an instance of some type is needed, but its state does not matter. An instance of object is perfect for this: public class ThreadSafe { private static readonly object locker = new object(); public void SomeThreadSafeMethod() { lock (locker) { ...
Locking on an stack-allocated / local variable One of the fallacies while using lock is the usage of local objects as locker in a function. Since these local object instances will differ on each call of the function, lock will not perform as expected. List<string> stringList = new List<st...

Page 1 of 1