What is the scope of the castle?

I saw this piece of code from one of the jetbrain team :

Looking at this code:

object myLock = new object() public IEnumerable<int> Values() { lock (myLock) { for (var i=0;i<10;i++) yield return i; } } public void Test() { foreach (var value in Values()) { DoHugeJob(value); } } void Main() { Test(); } 

Question:

What is the scope of lock ?

+5
source share
1 answer

If you mean it in terms of time, the lock will be implemented the first time MoveNext() called and will be released either when MoveNext() called for the 11th time (i.e. when the loop ends), or when the iterator is located.

For instance:

 var iterable = Values(); // Lock is *not* acquired yet... foreach (var item in iterable.Take(5)) { // Lock has been acquired } // Lock has been released even though we didn't get to the // end of the loop, because foreach calls Dispose 

In general, it is a bad idea to block iterator blocks because of this - you really want to block a short, easily understood period of your program.

+6
source

Source: https://habr.com/ru/post/1211486/


All Articles