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 :-/


 Anders Lybecker is an chief architect at Kring Development A/S, a consultancy firm in Copenhagen, Denmark. He holds a degree in software engineering specializing in software development. His primary expertises are the Microsoft .Net framework and SQL Server which he has been working with since the start of this century! He enjoys discussing technical topics, teaching and speaking at conferences.


Related posts:

  1. Favor structured exception handling
  2. Strings in .Net
  3. A simple Windows Communication Foundation Web Service

Tags:

One Response to “Monitors and thread context”

  1. Generally I don’t make comments on blogs, but I want to say that this post really forced me to do so. Really nice post!

Leave a Reply