When you say
lock (obj)
...
.NET uses the critical section in obj to synchronize the following statements.
How is this critical section initialized? (e.g. is it initialized at construction time, or lazily?)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Every object gets a 4 byte “block” of memory allocated to it (the syncblk) that is an index into a SyncTableEntry. When the object is created, the syncblk is assigned 0, which prevents any extra memory allocation (other than this 4 byte number). When a lock is taken, this syncblk is set to the appropriate entry in the table, which may then cause an allocation. In effect, it’s a lazy initialization.
When you call lock(object), this is effectively using
Monitor.Enteron the object, which in turn sets the entry appropriately. For details, see this MSDN article on .NET Memory Internals.