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:
- Favor structured exception handling
- Strings in .Net
- A simple Windows Communication Foundation Web Service
Tags: dotNet
This entry was posted
on Thursday, October 15th, 2009 at 8:27 pm and is filed under .Net, Code fun.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
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!