What is the correct way to block code areas

Which is better:
have a large area of ​​code in the lock instruction
or
have small locks in a large area? ..
exchanges in this sample do not change.

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));
  }
.....
+5
source share
5 answers

A wider lock - the less you get from multithreading, and vice versa. Thus, the use of locks is completely dependent on the logic. Block only those things and places that change and should only be started by one thread at a time

If you block the use of the collection sub, use a lower lock, but if you use several simultaneous loops in parallelforeach

+1
source

,

foreach,

, , ,

+1

, :
1. ?
2. ?

. , . "sub" , .

( - , , ).
, . , concurrency, .

+1

You cannot effectively judge what is “correct” with these code snippets. The first example says that people don't like to see sub with only a fraction of the content from exchanges. The second example says that it’s normal for people to see sub with only part of the content from exchanges.

0
source

All Articles