Alright, so here is the property I have
public List<String> names{
get{
lock(_names)
return _names;
}
set{
lock(_names)
_names = value
}
}
private List<String> _names;
and now say I do a foreach on names like this
foreach(String s in names)
{
Console.WriteLine(s);
}
My question is, is names locked through the whole foreach, or does it only lock each time s is set, then unlocks inside the foreach.
If that’s confusing, say I try to do this
foreach(String s in names)
{
lock(names)
Console.WriteLine(s);
}
Will I end up in a deadlock?
The
get_Namesmethod will only get called once, and the lock will be over (there will be no lock) during the iteration of the items. This is probably not what you intend and you should probably go for a much granular lock, such as:When you lock inside the loop, you will take many locks one after the other, which is almost certainly not what you want, since operating the foreach loop will not be atomic anymore.