2

I'm formerly a C++ developer and I read the C# docs on thread synchronization but one thing isn't clear to me.

The class creates a lock object specifically to be used for critical sections:

private System.Object lockThis = new System.Object();

Why can't they lock onto an existing object instead? For example, let's say that I have a class called "Players" which contains a list of players that is accessed from multiple threads via the singleton design pattern. It has "Add" and "Remove" methods.

Can I simply just lock this object instead of creating a new object to be used specifically for locks? if I can't why not?

I haven't found anything in the docs about this, as it seems to make the code look cleaner when this is done.

I.e., some psuedocode:

lock (Players)
{
    Players.Add(...);
    ...
    Players.Remove(...);
}

EDIT: Is this bad practice, discouraged, etc? Is that why it's not mentioned anywhere?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jason
  • 1,297
  • 12
  • 24
  • If you lock on an object that other parts of your code can access then those other parts may take the lock and cause your code to fail. By creating a private object you prevent that kind of bug. – Enigmativity Jul 25 '14 at 04:46
  • If I read that post correctly, it has to do with public objects. I didn't seem to mention it in my original post, but my Players class is private to my singleton class. Nothing else can modify the instance "Player" that is created. @Enigmativity ah okay, so it is just a suggestion then. A good coding practice, I guess. Should I delete this post? I'm not sure if someone else might find it handy. – Jason Jul 25 '14 at 04:46
  • 2
    Your class is private *today*. By locking on it, you are creating a *contract* that *no one in the future will change the exposure of the instance*, but if they do, nothing tells them that it is broken except for your comments, which they won't read. That's why the best practice is to lock an object whose *sole point of existing* is to be a lock; no one is going to expose that by accident. – Eric Lippert Jul 25 '14 at 04:53
  • 3
    To be perfectly frank, the idea that *any* instance of reference type can be the target of a lock is a bit of a misfeature that started (?) with Java and was continued in the CLR. It means that *every* instance of a reference type pays the price of a synchronization block even though literally more than 99.9999% of those objects will never be the target of a lock. I would rather have a dedicated type that is the only thing that can be locked. – Eric Lippert Jul 25 '14 at 04:57

0 Answers0