Re: what's wrong with lock(this) ?

From: Frans Bouma [C# MVP] (perseus.usenetNOSPAM_at_xs4all.nl)
Date: 04/10/04


Date: Sat, 10 Apr 2004 02:46:44 -0700

Jon Skeet [C# MVP] <skeet@pobox.com> wrote in
news:MPG.1ae0dcc09d78053998a64b@msnews.microsoft.com:
> Frans Bouma [C# MVP] <perseus.usenetNOSPAM@xs4all.nl> wrote:
>> lock() is most of the time used as a semaphore for a critical
>> action. To prevent multiple threads entering the same codeblock, an
>> object is locked (the parameter to lock()). THe bigger the object, the
>> more time it costs to lock it. So if you just want to prevent multiple
>> threads entering a codeblock, you'd better do this:

> While I agree with the idea of using a separate object, I disagree with
> your reasoning. In particular, I don't know of anything which makes it
> slower to lock a bigger object.
>
> The main reason (IMO) for avoiding locking on "this" is in case other
> classes are locking on the same reference. As soon as you lock on a
> reference which other classes have access to, you're at the whim of
> what those classes will be doing in terms of deadlocking etc. If you
> only ever lock on references which are only available within your own
> class, you get a lot more control. You can also have different locks
> separate "partitions" of exclusion.

            I re-read the thread on developmentor and I confused two things,
which caused my error. I stand corrected :)

                        Frans.

-- 
Get LLBLGen Pro, the new O/R mapper for .NET: http://www.llblgen.com
My .NET Blog: http://weblogs.asp.net/fbouma
Microsoft C# MVP


Relevant Pages