object theLock = new object();
...
lock (theLock)
{
...
}
I always use a new object() for this, but I’m wondering: are there any circumstances in which you would lock on a more specific type?
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.
In case of a
new, theTypedoesn’t matter, the instance do. In this case you’re talking about a synclock object : an object which is used to lock code(s) section(s) to prevent concurrent access.Using another
Typethanobjectfor a synclock is a waste of memory because you don’t use this instance for anything else.There’re circumstances in which you can lock another type : when you need to lock a specific instance.
The main problem is : the instance must be initialized to lock it. And in most cases, you want to synclock the initilization of the instance 🙂
But in some case, you can lock the instance directly ; like a dictionary for example (well almost directly in this case ;)).
But the point is : even if this will work, always ask yourself : “Is it not a better idea to create a specific locking object instead” ?