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?