Naming Convention for Dedicated Thread Locking objects
Posted
by
Chris Sinclair
on Programmers
See other posts from Programmers
or by Chris Sinclair
Published on 2012-10-10T15:33:19Z
Indexed on
2012/10/10
15:53 UTC
Read the original article
Hit count: 388
A relatively minor question, but I haven't been able to find official documentation or even blog opinion/discussions on it.
Simply put: when I have a private object whose sole purpose is to serve for private lock
, what do I name that object?
class MyClass
{
private object LockingObject = new object();
void DoSomething()
{
lock(LockingObject)
{
//do something
}
}
}
What should we name LockingObject
here? Also consider not just the name of the variable but how it looks in-code when locking.
I've seen various examples, but seemingly no solid go-to advice:
Plenty of usages of
SyncRoot
(and variations such as_syncRoot
).- Code Sample:
lock(SyncRoot)
,lock(_syncRoot)
- This appears to be influenced by VB's equivalent
SyncLock
statement, theSyncRoot
property that exists on some of the ICollection classes and part of some kind of SyncRoot design pattern (which arguably is a bad idea) - Being in a C# context, not sure if I'd want to have a VBish naming. Even worse, in VB naming the variable the same as the keyword. Not sure if this would be a source of confusion or not.
- Code Sample:
thisLock
andlockThis
from the MSDN articles: C# lock Statement, VB SyncLock Statement- Code Sample:
lock(thisLock)
,lock(lockThis)
- Not sure if these were named minimally purely for the example or not
- Kind of weird if we're using this within a
static
class/method.
- Code Sample:
Several usages of
PadLock
(of varying casing)- Code Sample:
lock(PadLock)
,lock(padlock)
- Not bad, but my only beef is it unsurprisingly invokes the image of a physical "padlock" which I tend to not associate with the abstract threading concept.
- Code Sample:
Naming the lock based on what it's intending to lock
- Code Sample:
lock(messagesLock)
,lock(DictionaryLock)
,lock(commandQueueLock)
- In the VB SyncRoot MSDN page example, it has a
simpleMessageList
example with a privatemessagesLock
object - I don't think it's a good idea to name the lock against the type you're locking around ("DictionaryLock") as that's an implementation detail that may change. I prefer naming around the concept/object you're locking ("messagesLock" or "commandQueueLock")
- Interestingly, I very rarely see this naming convention for locking objects in code samples online or on StackOverflow.
- Code Sample:
Question: What's your opinion generally about naming private locking objects?
Recently, I've started naming them ThreadLock
(so kinda like option 3), but I'm finding myself questioning that name.
I'm frequently using this locking pattern (in the code sample provided above) throughout my applications so I thought it might make sense to get a more professional opinion/discussion about a solid naming convention for them. Thanks!
© Programmers or respective owner