Monitors and thread context

Running the below code will fail – why?


var syncRoot = new object();

Monitor.Enter(syncRoot);

ThreadPool.QueueUserWorkItem(x => Monitor.Exit(syncRoot));

It will throw a SynchronizationLockException with the message “Object synchronization method was called from an unsynchronized block of code.”

It is because System.Threading.Monitor requires the Enter and Exit methods must be executed on the same thread for the same synchronization object.

I did not know that :-/