NetInverse Developers Blog

March 4, 2009
Category: .Net — Tags: , , , — admin @ 11:03 pm

Please read the following sample code with Monitor.Enter and Monitor.Exit. Does the lock work?

class LockMe
{
    private static int counter = 0;
    public void Lock()
    {
       Monitor.Enter(counter);
       counter++;
       Monitor.Exit(counter);
    }

No! The code actually is totally wrong. You are not supposed to lock a value type, which doesn’t have a SyncBlock field. Monitor.Enter(counter) will cause an int(counter) to be boxed first and then you are getting the lock from a box object, not the int itself. The lock won’t work as you expected, since a different object(a different SyncBlock) will be used each time.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

©2009 NetInverse. All rights reserved. Powered by WordPress