EDIT: As it turns out when I was browsing I found a question the appears to be the same as mine which I didn’t find earlier: Difference between lock(locker) and lock(variable_which_I_am_using)
I am looking at some code and trying to get my head around the locking thing and I am getting there I think.
Now I noticed in some code I am reviewing that an object is created like so:
private HashSet<Graphic> clustersInUse = new HashSet<Graphic>();
Then further in the code is used like so:
lock (clustersInUse)
{
// Do something with the Hashset
}
Now, is there a problem doing this rather than creating a specific object for the lock. Like this:
private object clusterLocker = new object();
What happens if the clustersInUse above somehow gets put into a public property, what happens then?
Also, if something tries to access the clustersInUse without locking it whilst it is locked in another thread what would happen then?
You’ve pretty much answered your own question. For locking, it’s generally better to create an object specifically for the purpose, and usually held privately for use by accessor methods that express synchronisation logic at a high level.