What is better:
to have large code area in lock statement
or
to have small locks in large area?..
exchanges in this sample are not changable.
lock (padLock)
{
foreach (string ex in exchanges)
{
sub.Add(x.ID, new Subscription(ch, queue.QueueName, true));
.........
}
or
foreach (string ex in exchanges)
{
lock (padLock)
{
sub.Add(x.ID, new Subscription(ch, queue.QueueName, true));
}
.....
The wider lock – the less you get from multithreading, and vice versa
So, use of locks completely depends on logic. Lock only things and places which changing and have to run only by one thread in a time
If you lock for using the collection
sub– use smaller lock, but if you run multiple simultaneousforeachloops in parallel