Frans Bouma [C# MVP] <pe******************@xs4all.nl> wrote:
n_**********@mail.com (n_o_s_p_a__m) wrote in
news:1f**************************@posting.google.c om:
I have seen some debate but am not clear on what the problematic
implications of the expression lock(this) are. Microsoft seems to
advocate it, but others seem to be against it.
Pros and cons?
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:
object uniqueObject = new object();
lock(uniqueObject)
{
// your code
}
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.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too