I was recently asked by a friend of mine who's just starting to play around with threading what the difference between using a secondary object purely for the purpose of locking or just locking the object you're referencing is. I had to admit that I had no idea, can anyone tell me? I will try and demonstrate with a couple of code snippets:
First method:
List<string> data = new List<string>();
object datalock = new object();
void main()
{
lock(datalock)
{
if (data.contains("SomeSearchString"))
{
//Do something with the data and then remove it
}
}
}
Second method:
List<string> data = new List<string>();
void main()
{
lock(data)
{
if (data.contains("SomeSearchString"))
{
//Do something with the data and then remove it
}
}
}
Is there a significant difference or is this down to personal coding style? If there is a significant difference, can anyone explain what it is?
I did come across another question [Difference between lock(locker) and lock(variable_which_I_am_using)] in which the answer implied that both of these are equivalent, but if that's the case, which would be the best to use and why?
I've seen a number of examples scattered around the net, I tend to use the first method as a matter of personal choice, but I wondered what the merits of using the second method would be.